@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
@@ -0,0 +1,439 @@
1
+ // Porta de SCM sobre o GitHub.
2
+ //
3
+ // ⚠️ REGRA DA FASE 1: `src/api/github-*.mjs` NÃO É EDITADO. Toda operação aqui
4
+ // é um forward de ≤3 linhas para um export que já existe. É o que torna
5
+ // "nenhuma mudança de comportamento" verificável em vez de esperançoso — a
6
+ // camada HTTP é literalmente os mesmos bytes, e todo o diff desta fase é sobre
7
+ // quem chama quem.
8
+ //
9
+ // Dois corolários que valem grep:
10
+ // • sem memoização que altere CONTAGEM de chamadas (mudaria retry, cota e
11
+ // net-cache de um jeito que nenhum teste enxerga);
12
+ // • sem reuso de instância Octokit — `makeOctokit(token)` continua nascendo
13
+ // por chamada, lá dentro.
14
+ //
15
+ // **Uma instância é UM repositório.** Em arquivo que lida com mais de um
16
+ // (`merge`, `code-review`, `qa`, `pr-ready`), identificador `scm` pelado é
17
+ // proibido: `hubScm`, `prScm`, `scmFor(link)`. Uma variável errada abre PR no
18
+ // repositório errado, e isso nenhum teste pega.
19
+
20
+ import { Octokit } from '@octokit/rest';
21
+
22
+ import {
23
+ commitFilesToBranch,
24
+ compareBranches,
25
+ deleteBranch,
26
+ deleteFile,
27
+ ensurePullRequest,
28
+ getBranchHead,
29
+ getFileContent,
30
+ getPR,
31
+ getRepoDefaultBranch,
32
+ getRepoNodeId,
33
+ getRepoVariable,
34
+ deleteRepoVariable,
35
+ isRepoInitialized,
36
+ listPullRequestCommitMessages,
37
+ listPullRequestReviews,
38
+ mergePR,
39
+ findOpenPR,
40
+ setRepoVariable,
41
+ updatePRBase,
42
+ upsertFile,
43
+ } from '../../api/github-rest.mjs';
44
+ import {
45
+ getPRClosingIssues,
46
+ getRateLimit,
47
+ listIssuePullRequests,
48
+ listOpenPullRequests,
49
+ markPullRequestReadyForReview,
50
+ } from '../../api/github-graphql.mjs';
51
+ import { refKey, refNumber } from '../../lib/work-item-ref.mjs';
52
+
53
+ /** @typedef {import('../../ports/types.mjs').ScmLink} ScmLink */
54
+ /** @typedef {import('../../ports/scm.mjs').ScmPort} ScmPort */
55
+
56
+ /** `kind` deste plugin — o valor gravado em `scm.kind` do .spec-wave.json. */
57
+ export const SCM_KIND = 'github';
58
+
59
+ /**
60
+ * O que o GitHub sabe fazer, na forma do `rfc/protocol/scm.v1.json`.
61
+ *
62
+ * Congelado: o core LÊ isto para degradar, e uma capability que pudesse ser
63
+ * mutada em runtime seria um plugin ganhando poder depois da carga.
64
+ */
65
+ export const GITHUB_SCM_CAPABILITIES = Object.freeze({
66
+ fileWrites: Object.freeze({
67
+ mode: 'tree-commit-ref',
68
+ atomicMultiFile: true,
69
+ concurrentPublishRetry: true,
70
+ }),
71
+ pullRequests: Object.freeze({
72
+ draft: true,
73
+ retarget: true,
74
+ mergeStrategies: Object.freeze(['merge', 'squash', 'rebase']),
75
+ reviewModel: 'decision',
76
+ referenceSearch: true,
77
+ }),
78
+ variables: 'repo',
79
+ automation: 'github-actions',
80
+ remoteDispatch: Object.freeze({ mechanism: 'repository-dispatch' }),
81
+ identity: Object.freeze({
82
+ configKeys: Object.freeze(['owner', 'repo']),
83
+ branchNameConstraints: Object.freeze({ maxLength: 255 }),
84
+ }),
85
+ });
86
+
87
+ /**
88
+ * Monta o `ScmLink` de um par owner/repo (função PURA).
89
+ *
90
+ * O `id` é a chave estável do core para mapa, cache e deduplicação de PR. Leva
91
+ * o `kind` na frente porque um dia vão conviver dois fornecedores no mesmo
92
+ * workspace, e `acme/api` sozinho não diz de qual.
93
+ *
94
+ * @param {{owner: string, repo: string, role?: 'hub'|'code'}} params
95
+ * @returns {ScmLink}
96
+ */
97
+ export function githubLink({ owner, repo, role = 'hub' }) {
98
+ return {
99
+ id: `${SCM_KIND}:${owner}/${repo}`,
100
+ kind: SCM_KIND,
101
+ role,
102
+ label: `${owner}/${repo}`,
103
+ config: { owner, repo },
104
+ };
105
+ }
106
+
107
+ /** Normaliza o PR devolvido pela REST (`getPR`, `findOpenPR`). */
108
+ function prFromRest(raw, link) {
109
+ if (!raw) return null;
110
+ return {
111
+ id: raw.node_id || String(raw.id || ''),
112
+ number: String(raw.number),
113
+ url: raw.html_url || null,
114
+ title: raw.title || '',
115
+ body: raw.body || '',
116
+ state: raw.merged_at ? 'merged' : String(raw.state || 'open').toLowerCase(),
117
+ draft: Boolean(raw.draft),
118
+ baseRef: raw.base?.ref ?? raw.base ?? null,
119
+ headRef: raw.head?.ref ?? null,
120
+ createdAt: raw.created_at ?? null,
121
+ link,
122
+ };
123
+ }
124
+
125
+ /** Normaliza o PR devolvido pelo GraphQL (`listOpenPullRequests`, `listIssuePullRequests`). */
126
+ function prFromGraphql(raw, link) {
127
+ if (!raw) return null;
128
+ return {
129
+ id: raw.id,
130
+ number: String(raw.number),
131
+ url: raw.url || null,
132
+ title: raw.title || '',
133
+ body: raw.body || '',
134
+ state: raw.merged ? 'merged' : String(raw.state || 'open').toLowerCase(),
135
+ draft: Boolean(raw.isDraft),
136
+ baseRef: raw.baseRefName || null,
137
+ headRef: raw.headRefName || null,
138
+ createdAt: raw.createdAt ?? null,
139
+ link,
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Normaliza uma run de workflow do Actions (função PURA — exportada p/ teste).
145
+ *
146
+ * `AutomationRun` é o tipo que uma pipeline do Azure DevOps também precisa
147
+ * caber; por isso `conclusion` é normalizada para o enum do contrato e o que
148
+ * não couber vira null em vez de vazar a string do fornecedor.
149
+ */
150
+ export function toAutomationRun(raw) {
151
+ const CONCLUSOES = ['success', 'failure', 'cancelled', 'skipped', 'timed_out', 'action_required'];
152
+ // `startup_failure` é o workflow que nem chegou a começar (YAML inválido,
153
+ // permissão faltando). É falha, e o remédio é o mesmo — um valor próprio
154
+ // significando "falhou, só que antes" não mudaria decisão nenhuma.
155
+ const SINONIMOS = { startup_failure: 'failure' };
156
+ const cru = String(raw?.conclusion || '').toLowerCase();
157
+ const conclusion = SINONIMOS[cru] || cru;
158
+ const status = String(raw?.status || '').toLowerCase();
159
+ return {
160
+ id: String(raw?.id ?? ''),
161
+ name: raw?.name || raw?.workflow_id || '',
162
+ status: ['queued', 'in_progress', 'completed'].includes(status) ? status : 'queued',
163
+ // `neutral` e `stale` caem aqui de propósito: "terminou sem veredito" já é
164
+ // o que `completed` + null diz, e inventar valor para eles só espalharia
165
+ // um caso que ninguém trata.
166
+ conclusion: CONCLUSOES.includes(conclusion) ? conclusion : null,
167
+ createdAt: raw?.created_at || '',
168
+ url: raw?.html_url || null,
169
+ headBranch: raw?.head_branch || null,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * A cláusula de fechamento que liga um PR ao work item (função PURA).
175
+ *
176
+ * Duas regras, e as duas já existem no fluxo de hoje:
177
+ *
178
+ * • Tracker de outro fornecedor ⇒ `null`. `Closes #N` é sintaxe do GitHub, e o
179
+ * GitHub não fecha uma issue do Jira. Nesse caso o fechamento passa a ser
180
+ * explícito, pela porta de tracker — mais verboso e mais previsível que o
181
+ * efeito hoje implícito.
182
+ * • PR fora do hub ⇒ forma QUALIFICADA `owner/repo#n`. Com um hub e N repos de
183
+ * código (RFC-005) a issue vive no hub e o PR não; `#N` solto ali aponta
184
+ * para uma issue do repo de código — outra issue, ou nenhuma.
185
+ *
186
+ * @param {{ref: object, trackerKind: string, prLink: ScmLink, hubLink: ScmLink}} params
187
+ * @returns {string|null}
188
+ */
189
+ export function githubClosingKeyword({ ref, trackerKind, prLink, hubLink } = {}) {
190
+ if (trackerKind !== 'github-projects') return null;
191
+ const key = refKey(ref);
192
+ if (!key) return null;
193
+ const mesmoRepo = !prLink || !hubLink || prLink.id === hubLink.id;
194
+ return mesmoRepo ? `Closes #${key}` : `Closes ${hubLink.label}#${key}`;
195
+ }
196
+
197
+ /**
198
+ * Cria a porta de SCM do GitHub presa a UM repositório.
199
+ *
200
+ * @param {object} params
201
+ * @param {ScmLink} params.link repositório desta instância (ver githubLink)
202
+ * @param {string} params.token credencial padrão
203
+ * @param {string} [params.prToken] credencial usada SÓ para abrir Pull Request.
204
+ * Existe porque `GH_PR_TOKEN`/`SPEC_WAVE_PR_TOKEN` é o contorno de "Allow
205
+ * GitHub Actions to create and approve pull requests" desligado: o commit vai
206
+ * com o token do job, o PR não pode. Colapsar os dois quebraria a publicação
207
+ * de documento em toda organização com essa opção fechada.
208
+ * @param {string} [params.trackerKind] com qual tracker esta instância foi
209
+ * pareada. Injetado pelo CORE: nenhum plugin de SCM sabe isso sozinho, e é
210
+ * disso que `closingKeyword` e o vínculo nativo dependem.
211
+ * @param {object} [params.api] injeção para teste — mesmo seam do `deps = {}`
212
+ * que `lib/artifact-publish.mjs` já usa.
213
+ * @returns {ScmPort}
214
+ */
215
+ export function createGithubScm({ link, token, prToken, trackerKind = 'github-projects', api = {} } = {}) {
216
+ if (!link?.config?.owner || !link?.config?.repo) {
217
+ throw new Error('createGithubScm: `link` precisa de config.owner e config.repo (ver githubLink).');
218
+ }
219
+ const { owner, repo } = link.config;
220
+ const tk = prToken || token;
221
+
222
+ const a = {
223
+ commitFilesToBranch, compareBranches, deleteBranch, deleteFile, ensurePullRequest,
224
+ getBranchHead, getFileContent, getPR, getRepoDefaultBranch, getRepoNodeId,
225
+ getRepoVariable, deleteRepoVariable, isRepoInitialized, listPullRequestCommitMessages,
226
+ listPullRequestReviews, mergePR, findOpenPR, setRepoVariable, updatePRBase, upsertFile,
227
+ getPRClosingIssues, getRateLimit, listIssuePullRequests, listOpenPullRequests,
228
+ markPullRequestReadyForReview,
229
+ ...api,
230
+ };
231
+
232
+ return {
233
+ kind: SCM_KIND,
234
+ link,
235
+ capabilities: GITHUB_SCM_CAPABILITIES,
236
+
237
+ async setup() {
238
+ // O GitHub não precisa de provisionamento de repositório: ele já existe
239
+ // (é onde o comando roda). A automação é publicada por installAutomation.
240
+ return { warnings: [] };
241
+ },
242
+
243
+ async verify() {
244
+ const problems = [];
245
+ const facts = {};
246
+ // Sonda de alcance: é o que `commands/repo.mjs` já faz hoje, chamando
247
+ // getRepoNodeId e descartando o retorno. O que importa é o 404/403.
248
+ try {
249
+ facts.repoNodeId = await a.getRepoNodeId(token, owner, repo);
250
+ } catch (err) {
251
+ problems.push(`repositório ${link.label} inacessível: ${err.message}`);
252
+ }
253
+ const quota = (await a.getRateLimit(token)) || {};
254
+ return {
255
+ ok: problems.length === 0,
256
+ quota: {
257
+ remaining: quota.remaining ?? null,
258
+ limit: quota.limit ?? null,
259
+ resetAt: quota.resetAt ?? null,
260
+ },
261
+ facts,
262
+ problems,
263
+ };
264
+ },
265
+
266
+ defaultBranch() {
267
+ return a.getRepoDefaultBranch(token, owner, repo);
268
+ },
269
+
270
+ isInitialized() {
271
+ return a.isRepoInitialized(token, owner, repo);
272
+ },
273
+
274
+ readFile({ path: p, ref } = {}) {
275
+ return a.getFileContent(token, owner, repo, p, ref);
276
+ },
277
+
278
+ writeFiles({ branch, base, files, message } = {}) {
279
+ return a.commitFilesToBranch(token, owner, repo, {
280
+ branch, base, message,
281
+ files: (files || []).map(f => ({ path: f.path, content: f.content })),
282
+ });
283
+ },
284
+
285
+ deleteFile({ path: p, message } = {}) {
286
+ return a.deleteFile(token, owner, repo, p, message);
287
+ },
288
+
289
+ branchHead({ branch } = {}) {
290
+ return a.getBranchHead(token, owner, repo, branch);
291
+ },
292
+
293
+ compare({ base, head } = {}) {
294
+ return a.compareBranches(token, owner, repo, base, head);
295
+ },
296
+
297
+ deleteBranch({ branch } = {}) {
298
+ return a.deleteBranch(token, owner, repo, branch);
299
+ },
300
+
301
+ async findOpenPullRequest({ branch } = {}) {
302
+ const pr = await a.findOpenPR(token, owner, repo, branch);
303
+ // findOpenPR devolve {number, url, title, base} — forma enxuta própria.
304
+ return pr ? prFromRest({ ...pr, base: pr.base, html_url: pr.url }, link) : null;
305
+ },
306
+
307
+ async ensurePullRequest({ branch, base, title, body, draft = false } = {}) {
308
+ // prToken e SÓ aqui: é a única chamada que a política de credencial de PR
309
+ // cobre. Ver o parâmetro `prToken` acima.
310
+ const res = await a.ensurePullRequest(tk, owner, repo, { branch, base, title, body, draft });
311
+ if (!res) return { pr: null, created: false };
312
+ return {
313
+ pr: prFromRest({ ...res, html_url: res.url, base: res.base }, link),
314
+ created: Boolean(res.created),
315
+ };
316
+ },
317
+
318
+ async getPullRequest({ number } = {}) {
319
+ return prFromRest(await a.getPR(token, owner, repo, Number(number)), link);
320
+ },
321
+
322
+ listPullRequestCommitMessages({ number } = {}) {
323
+ return a.listPullRequestCommitMessages(token, owner, repo, Number(number));
324
+ },
325
+
326
+ async listPullRequestReviews({ number } = {}) {
327
+ const cruas = await a.listPullRequestReviews(token, owner, repo, Number(number));
328
+ // CRU por revisor: quem agrega é reviewDecision(), no core. Um plugin que
329
+ // normalizasse aqui faria dois plugins `vote` decidirem diferente.
330
+ return (cruas || []).map(r => ({
331
+ reviewer: r.user?.login || '',
332
+ submittedAt: r.submitted_at || null,
333
+ state: String(r.state || '').toUpperCase(),
334
+ }));
335
+ },
336
+
337
+ async listOpenPullRequests() {
338
+ const prs = await a.listOpenPullRequests(token, owner, repo);
339
+ return (prs || []).map(p => prFromGraphql(p, link));
340
+ },
341
+
342
+ mergePullRequest({ number, strategy = 'merge' } = {}) {
343
+ return a.mergePR(token, owner, repo, Number(number), { method: strategy });
344
+ },
345
+
346
+ closingKeyword({ ref, trackerKind: tkind, prLink, hubLink } = {}) {
347
+ return githubClosingKeyword({ ref, trackerKind: tkind ?? trackerKind, prLink, hubLink });
348
+ },
349
+
350
+ fileUrl({ ref, pathRel } = {}) {
351
+ // A ref NÃO é escapada de propósito: branch com `/` (feat/x) funciona crua
352
+ // na URL do GitHub, e encodeURIComponent a quebraria.
353
+ return `https://github.com/${owner}/${repo}/blob/${ref}/${pathRel}`;
354
+ },
355
+
356
+ async listAutomationRuns({ branch, limit = 20 } = {}) {
357
+ const octokit = new Octokit({ auth: token });
358
+ const res = await octokit.request('GET /repos/{owner}/{repo}/actions/runs', {
359
+ owner, repo, per_page: limit, ...(branch ? { branch } : {}),
360
+ });
361
+ return (res.data?.workflow_runs || []).map(toAutomationRun);
362
+ },
363
+
364
+ markReadyForReview({ id } = {}) {
365
+ // Só existe em GraphQL: a REST ignora o PATCH de `draft` em silêncio, que
366
+ // é pior que recusar.
367
+ return a.markPullRequestReadyForReview(token, id);
368
+ },
369
+
370
+ setPullRequestBase({ number, base } = {}) {
371
+ return a.updatePRBase(token, owner, repo, Number(number), base);
372
+ },
373
+
374
+ async findPullRequestsReferencing({ ref } = {}) {
375
+ // Vínculo NATIVO quando o tracker também é GitHub — é o
376
+ // `closedByPullRequestsReferences` alimentado por `Closes #N`, e é o que
377
+ // dá a precisão de hoje (zero regressão). Consome o NODE ID, que é a
378
+ // razão de WorkItemRef carregar um opaco.
379
+ if (trackerKind === 'github-projects' && ref?.id) {
380
+ const prs = await a.listIssuePullRequests(token, ref.id);
381
+ return (prs || []).map(p => prFromGraphql(p, link));
382
+ }
383
+ // Qualquer outra combinação: busca nos PRs abertos e casamento da chave,
384
+ // sob a política de `codeReview.linkMode` que já existe.
385
+ const key = refKey(ref);
386
+ if (!key) return [];
387
+ const abertos = await a.listOpenPullRequests(token, owner, repo);
388
+ return (abertos || [])
389
+ .filter(p => new RegExp(`#${key}\\b`).test(p.body || ''))
390
+ .map(p => prFromGraphql(p, link));
391
+ },
392
+
393
+ /**
394
+ * Os work items que o GitHub reconhece como fechados por este PR — a
395
+ * inversa de findPullRequestsReferencing, pela mesma fonte de vínculo.
396
+ */
397
+ async getPullRequestClosingWorkItems({ number } = {}) {
398
+ const nums = await a.getPRClosingIssues(token, owner, repo, Number(number));
399
+ return (nums || []).map(n => String(n));
400
+ },
401
+
402
+ getVariable({ name } = {}) {
403
+ return a.getRepoVariable(token, owner, repo, name);
404
+ },
405
+
406
+ setVariable({ name, value } = {}) {
407
+ return a.setRepoVariable(token, owner, repo, name, value);
408
+ },
409
+
410
+ deleteVariable({ name } = {}) {
411
+ return a.deleteRepoVariable(token, owner, repo, name);
412
+ },
413
+
414
+ async installAutomation({ files = [], log } = {}) {
415
+ // upsertFile e não writeFiles de propósito: o `init` commita DIRETO na
416
+ // branch default, um commit por arquivo. Trocar por um commit atômico
417
+ // mudaria o histórico observável do init — e esta fase não muda
418
+ // comportamento. A unificação é da Fase 2.
419
+ const written = [];
420
+ for (let i = 0; i < files.length; i++) {
421
+ const f = files[i];
422
+ log?.({ index: i, total: files.length, path: f.path });
423
+ await a.upsertFile(token, owner, repo, f.path, f.content, f.message);
424
+ written.push(f.path);
425
+ }
426
+ return { written, skipped: [] };
427
+ },
428
+
429
+ async dispatch({ action, key } = {}) {
430
+ const octokit = new Octokit({ auth: token });
431
+ await octokit.request('POST /repos/{owner}/{repo}/dispatches', {
432
+ owner, repo, event_type: action, client_payload: { action, key: refKey(key) },
433
+ });
434
+ },
435
+ };
436
+ }
437
+
438
+ /** Reexportado para quem precisa converter chave → número na fronteira. */
439
+ export { refNumber };
@@ -0,0 +1,73 @@
1
+ // Endereçamento de campo do GitHub Projects v2 — o que SAI do core.
2
+ //
3
+ // O core fala nomes CANÔNICOS (`workItemType`); o Projects v2 endereça por
4
+ // rótulo de exibição ("Work Item Type"), id de campo e id de OPÇÃO. Traduzir é
5
+ // o que um `fieldMap` de Jira faria, e é por isso que esta tradução mora no
6
+ // plugin e não em `lib/board.mjs`.
7
+ //
8
+ // Aqui também vive `resolveField`, que saiu de `lib/board.mjs:49` sem mudar de
9
+ // corpo, incluindo o caminho LEGADO (`etapaFieldId`/`stageOptions`). Esse
10
+ // caminho não é código morto: é o formato que o `init` da 0.16.4 gravou, e o
11
+ // spec-wave-agent ainda tem um `.spec-wave.json` daquela época.
12
+
13
+ import { getSingleSelectField } from '../../api/github-graphql.mjs';
14
+
15
+ /**
16
+ * Nome canônico → rótulo de exibição do campo no board.
17
+ *
18
+ * `stage` e `progress` entram aqui mesmo não sendo `FieldName`: os três são
19
+ * endereçados do mesmo jeito no Projects v2 (single-select com opções), e
20
+ * separá-los criaria duas tabelas com a mesma forma.
21
+ */
22
+ export const FIELD_LABEL = Object.freeze({
23
+ stage: 'Etapa',
24
+ progress: 'Status',
25
+ workItemType: 'Work Item Type',
26
+ priority: 'Priority',
27
+ storyPoints: 'Story Points',
28
+ area: 'Area',
29
+ release: 'Release',
30
+ });
31
+
32
+ /** Rótulo de exibição → nome canônico (o inverso, para ler o snapshot). */
33
+ export const FIELD_CANONICAL = Object.freeze(
34
+ Object.fromEntries(Object.entries(FIELD_LABEL).map(([canonico, rotulo]) => [rotulo, canonico]))
35
+ );
36
+
37
+ /**
38
+ * Resolve um campo SINGLE_SELECT pelo nome canônico.
39
+ *
40
+ * Três fontes, nesta ordem — e a ordem é a razão de a função existir:
41
+ * 1. os ids gravados em `project.fields` pelo `init`/`refresh` (sem rede);
42
+ * 2. o formato LEGADO `etapaFieldId`/`stageOptions`, só para "Etapa";
43
+ * 3. a API, como último recurso.
44
+ *
45
+ * @param {object} params
46
+ * @param {string} params.token credencial com escopo de project
47
+ * @param {object} params.project bloco `project` do .spec-wave.json
48
+ * @param {string} params.field nome canônico (chave de FIELD_LABEL)
49
+ * @returns {Promise<{id: string, options: Record<string,string>}|null>}
50
+ */
51
+ export async function resolveField({ token, project, field }) {
52
+ const rotulo = FIELD_LABEL[field] || field;
53
+ if (project?.fields?.[rotulo]) return project.fields[rotulo];
54
+ if (rotulo === 'Etapa' && project?.etapaFieldId) {
55
+ return { id: project.etapaFieldId, options: project.stageOptions || {} };
56
+ }
57
+ return await getSingleSelectField(token, project.id, rotulo);
58
+ }
59
+
60
+ /**
61
+ * O id da opção `valor` dentro de um campo (função PURA).
62
+ *
63
+ * Devolve null quando a opção não existe — quem chama decide se isso é board
64
+ * divergente (a Etapa, onde é erro nomeado) ou campo opcional (o resto, onde
65
+ * é no-op).
66
+ *
67
+ * @param {{options?: Record<string,string>}|null} campo
68
+ * @param {string} valor
69
+ * @returns {string|null}
70
+ */
71
+ export function optionId(campo, valor) {
72
+ return campo?.options?.[valor] ?? null;
73
+ }