@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
@@ -0,0 +1,662 @@
1
+ // Porta de TRACKER sobre GitHub Issues + Projects v2.
2
+ //
3
+ // Mesma regra da porta de SCM: `src/api/github-*.mjs` NÃO é editado, e toda
4
+ // operação é um forward para um export que já existe. As poucas que não têm
5
+ // equivalente hoje (`listWorkItemsByTag`) usam octokit direto — não há
6
+ // comportamento a preservar onde não há chamador.
7
+ //
8
+ // ── Duas credenciais, e por que não uma ──────────────────────────────────
9
+ //
10
+ // `token` faz REST de issue (comentário, label, estado); `projectToken` faz
11
+ // Projects v2. Hoje quatro comandos e uma lib usam
12
+ // `process.env.PROJECT_TOKEN || token` SÓ para o board, com o `token` simples
13
+ // fazendo as issues no mesmo comando. Uma porta presa a uma credencial
14
+ // promoveria PROJECT_TOKEN às chamadas de issue — e um PAT com escopo
15
+ // `project` e sem `repo` no hub daria 403 que nenhum teste desta suíte
16
+ // enxerga, porque não há mock de HTTP.
17
+ //
18
+ // ── O memo, e por que ele NÃO viola a regra de contagem de chamadas ──────
19
+ //
20
+ // `getStage` + `setStage` substituem um `advanceToStage` que chamava
21
+ // `addProjectItem` uma vez. Sem memo, o par chamaria duas — em dez call sites.
22
+ // O memo por instância REPÕE a contagem de hoje; ele não a reduz abaixo dela.
23
+
24
+ import { Octokit } from '@octokit/rest';
25
+
26
+ import {
27
+ addBlockedBy,
28
+ addLabel,
29
+ commentOnIssue,
30
+ countOpenIssuesWithLabel,
31
+ createIssue,
32
+ createLabel,
33
+ createMilestone,
34
+ deleteLabel,
35
+ getIssue,
36
+ getMilestone,
37
+ getOwnerType,
38
+ listBlockedBy,
39
+ listIssueComments,
40
+ listIssuesByMilestone,
41
+ listLabels,
42
+ listMilestones,
43
+ removeLabel,
44
+ setIssueMilestone,
45
+ setIssueState,
46
+ updateComment,
47
+ updateLabel,
48
+ updateMilestone,
49
+ updateMilestoneDescription,
50
+ getOwnerNodeId,
51
+ getRepoNodeId,
52
+ } from '../../api/github-rest.mjs';
53
+ import {
54
+ addProjectItem,
55
+ addSubIssue,
56
+ createProject,
57
+ createSingleSelectField,
58
+ createTextField,
59
+ getIssueParent,
60
+ getItemSingleSelectValue,
61
+ getItemTextValue,
62
+ setItemText,
63
+ getProjectSnapshot,
64
+ getRateLimit,
65
+ linkProjectToRepo,
66
+ listProjectItems,
67
+ listSubIssues,
68
+ setItemSingleSelect,
69
+ } from '../../api/github-graphql.mjs';
70
+ import { CUSTOM_FIELDS, STATUS_OPTIONS, labelNames } from '../../config.mjs';
71
+ import { refKey, refNumber, workItemRef } from '../../lib/work-item-ref.mjs';
72
+ import { FIELD_CANONICAL, FIELD_LABEL, optionId, resolveField } from './fields.mjs';
73
+
74
+ /** @typedef {import('../../ports/tracker.mjs').TrackerPort} TrackerPort */
75
+
76
+ export const TRACKER_KIND = 'github-projects';
77
+
78
+ /**
79
+ * O que o GitHub Projects v2 sabe fazer, na forma de `tracker.v1.json`.
80
+ */
81
+ export const GITHUB_TRACKER_CAPABILITIES = Object.freeze({
82
+ hierarchy: 'native', // sub-issues
83
+ dependencies: 'native', // API de dependencies (blocked_by)
84
+ milestones: 'native',
85
+ stages: Object.freeze({ mode: 'set', multiHop: false, reopenable: true }),
86
+ progress: 'native', // o campo nativo "Status" do Projects v2
87
+ fields: Object.freeze({
88
+ stage: 'native', workItemType: 'native', priority: 'native',
89
+ storyPoints: 'native', area: 'native', release: 'native',
90
+ }),
91
+ workItemTypes: 'create',
92
+ boardProvisioning: 'create',
93
+ commentFormat: 'markdown',
94
+ commentMarkers: true,
95
+ tagConstraints: Object.freeze({ maxLength: 50, colors: true, descriptions: true }),
96
+ closeSemantics: 'state',
97
+ // `^[1-9][0-9]*$` e não `^[0-9]+$`: issue 0 não existe no GitHub, e `007` não
98
+ // é como ele endereça a issue 7. Um pattern que aceita as duas descreve o
99
+ // fornecedor errado, e é esse pattern que a Fase 2 vai usar para validar
100
+ // chave de entrada.
101
+ identity: Object.freeze({ keyPattern: '^[1-9][0-9]*$', keyIsNumeric: true, branchSafe: true }),
102
+ });
103
+
104
+ /**
105
+ * O campo "Etapa" — as 12 colunas do RFC-001.
106
+ *
107
+ * O Projects v2 não deixa substituir as opções do campo Status nativo de forma
108
+ * atômica ("Position has already been taken"), então o fluxo tem um
109
+ * single-select próprio e a view do board agrupa por ele.
110
+ */
111
+ const ETAPA_FIELD = { name: 'Etapa', dataType: 'SINGLE_SELECT', options: STATUS_OPTIONS };
112
+
113
+ /**
114
+ * `state_reason` do GitHub → o vocabulário canônico.
115
+ *
116
+ * O GitHub grafa com `_`, o contrato com `-`; e `reopened` só existe enquanto a
117
+ * issue está aberta. Traduzir aqui é o que impede a grafia do fornecedor de
118
+ * virar comparação literal no core.
119
+ */
120
+ function toStateReason(raw) {
121
+ const v = String(raw || '').toLowerCase();
122
+ if (v === 'completed') return 'completed';
123
+ if (v === 'not_planned') return 'not-planned';
124
+ if (v === 'reopened') return 'reopened';
125
+ return null;
126
+ }
127
+
128
+ /** Normaliza uma issue da REST para o `WorkItem` do contrato. */
129
+ function toWorkItem(raw) {
130
+ if (!raw) return null;
131
+ return {
132
+ ref: workItemRef({ key: raw.number, id: raw.node_id || null, url: raw.html_url || null }),
133
+ title: raw.title || '',
134
+ body: raw.body || '',
135
+ state: String(raw.state || 'open').toLowerCase() === 'closed' ? 'closed' : 'open',
136
+ tags: labelNames(raw),
137
+ milestone: raw.milestone
138
+ ? {
139
+ key: String(raw.milestone.number),
140
+ title: raw.milestone.title || '',
141
+ dueOn: raw.milestone.due_on ?? null,
142
+ }
143
+ : null,
144
+ createdAt: raw.created_at || null,
145
+ stateReason: toStateReason(raw.state_reason),
146
+ };
147
+ }
148
+
149
+ /** Normaliza uma milestone da REST para o `MilestoneRef` do contrato. */
150
+ function toMilestone(raw) {
151
+ if (!raw) return null;
152
+ return {
153
+ key: String(raw.number),
154
+ title: raw.title || '',
155
+ dueOn: raw.due_on ?? null,
156
+ description: raw.description || '',
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Cria a porta de tracker do GitHub Projects v2.
162
+ *
163
+ * @param {object} params
164
+ * @param {string} params.token credencial padrão (REST de issue)
165
+ * @param {string} [params.projectToken] credencial do board; ausente = `token`
166
+ * @param {string} params.owner
167
+ * @param {string} params.repo
168
+ * @param {object} [params.project] bloco `project` do .spec-wave.json
169
+ * @param {object} [params.api] injeção para teste
170
+ * @returns {TrackerPort}
171
+ */
172
+ export function createGithubTracker({ token, projectToken, owner, repo, project = null, api = {} } = {}) {
173
+ if (!owner || !repo) throw new Error('createGithubTracker: owner e repo são obrigatórios.');
174
+ const ptk = projectToken || token;
175
+
176
+ const a = {
177
+ addBlockedBy, addLabel, commentOnIssue, countOpenIssuesWithLabel, createIssue, createLabel,
178
+ createMilestone, deleteLabel, getIssue, getMilestone, getOwnerType, listBlockedBy,
179
+ listIssueComments, listIssuesByMilestone, listLabels, listMilestones, removeLabel,
180
+ setIssueMilestone, setIssueState, updateComment, updateLabel, updateMilestone,
181
+ updateMilestoneDescription, getOwnerNodeId, getRepoNodeId,
182
+ addProjectItem, addSubIssue, createProject, createSingleSelectField, createTextField,
183
+ getIssueParent, getItemSingleSelectValue, getItemTextValue, getProjectSnapshot, getRateLimit,
184
+ linkProjectToRepo, listProjectItems, listSubIssues, setItemSingleSelect, setItemText,
185
+ resolveField,
186
+ ...api,
187
+ };
188
+
189
+ // key → { nodeId, dbId, itemId }. Por instância, nunca global.
190
+ //
191
+ // O GitHub tem TRÊS identificadores por issue e `WorkItemRef` só tem espaço
192
+ // para dois: number (a key), node id (o opaco) e o DATABASE id, que é o que a
193
+ // API de dependencies exige. O terceiro mora aqui.
194
+ const memo = new Map();
195
+ const slot = key => {
196
+ if (!memo.has(key)) memo.set(key, { nodeId: null, dbId: null, itemId: null });
197
+ return memo.get(key);
198
+ };
199
+
200
+ /**
201
+ * Garante o identificador PEDIDO para um ref, buscando a issue só se faltar.
202
+ *
203
+ * `need` importa: quase todo call site quer só o node id, e o ref já o traz.
204
+ * Exigir `dbId` sempre pagaria um `getIssue` por item em todo movimento de
205
+ * board — a deriva de contagem de chamadas que esta fase existe para não ter.
206
+ * Só a API de dependencies precisa do database id.
207
+ *
208
+ * @param {object|string|number} ref
209
+ * @param {{ need?: 'node' | 'db' }} [opts]
210
+ */
211
+ async function hidratar(ref, { need = 'node' } = {}) {
212
+ const key = refKey(ref);
213
+ if (!key) throw new Error('Operação de tracker sem chave de work item.');
214
+ const s = slot(key);
215
+ if (ref?.id && !s.nodeId) s.nodeId = ref.id;
216
+ const falta = need === 'db' ? (!s.nodeId || !s.dbId) : !s.nodeId;
217
+ if (falta) {
218
+ const raw = await a.getIssue(token, owner, repo, refNumber(key));
219
+ s.nodeId = raw?.node_id || s.nodeId;
220
+ s.dbId = raw?.id ?? s.dbId;
221
+ }
222
+ return { key, ...s };
223
+ }
224
+
225
+ /** O item do board correspondente, criando-o se ainda não existir. */
226
+ async function itemDoBoard(ref) {
227
+ const { key, nodeId } = await hidratar(ref);
228
+ const s = slot(key);
229
+ if (!s.itemId) s.itemId = await a.addProjectItem(ptk, project.id, nodeId);
230
+ return s.itemId;
231
+ }
232
+
233
+ const campo = field => a.resolveField({ token: ptk, project, field });
234
+
235
+ /** @type {TrackerPort} */
236
+ const porta = {
237
+ kind: TRACKER_KIND,
238
+ capabilities: GITHUB_TRACKER_CAPABILITIES,
239
+
240
+ async setup({ provision = true, title, log } = {}) {
241
+ // `provision: false` é LEITURA: devolve o bloco de config que descreve o
242
+ // board como ele está agora. É o que o `refresh --config` precisa, e é a
243
+ // mesma pergunta que um tracker `map-only` responderia relendo os
244
+ // statuses do site — por isso não virou operação separada.
245
+ if (!provision) {
246
+ const snap = await a.getProjectSnapshot(ptk, project?.id);
247
+ if (!snap) {
248
+ return { config: null, warnings: [`Project ${project?.id} não encontrado. Ele pode ter sido excluído.`] };
249
+ }
250
+ return {
251
+ config: {
252
+ projectId: snap.id,
253
+ projectNumber: snap.number,
254
+ projectUrl: snap.url,
255
+ projectTitle: snap.title,
256
+ fields: snap.fields,
257
+ },
258
+ warnings: [],
259
+ };
260
+ }
261
+ const aviso = m => log?.(m);
262
+ aviso('Buscando IDs do owner e repositório...');
263
+ const [ownerId, repositoryId] = await Promise.all([
264
+ a.getOwnerNodeId(token, owner),
265
+ a.getRepoNodeId(token, owner, repo),
266
+ ]);
267
+
268
+ aviso('Criando GitHub Project...');
269
+ const { projectId, projectNumber, projectUrl } = await a.createProject(token, ownerId, title);
270
+
271
+ aviso('Criando campos customizados...');
272
+ const selectFields = CUSTOM_FIELDS.filter(f => f.dataType === 'SINGLE_SELECT');
273
+ const textFields = CUSTOM_FIELDS.filter(f => f.dataType === 'TEXT');
274
+
275
+ // SEQUENCIAL: o Projects v2 responde "Position has already been taken"
276
+ // quando dois SINGLE_SELECT são criados ao mesmo tempo.
277
+ const fields = {};
278
+ for (const f of [ETAPA_FIELD, ...selectFields]) {
279
+ aviso(`Criando campo "${f.name}"...`);
280
+ fields[f.name] = await a.createSingleSelectField(token, projectId, f.name, f.options);
281
+ }
282
+ for (const f of textFields) {
283
+ aviso(`Criando campo "${f.name}"...`);
284
+ await a.createTextField(token, projectId, f.name);
285
+ }
286
+
287
+ const config = { projectId, projectNumber, projectUrl, fields };
288
+ try {
289
+ aviso('Vinculando projeto ao repositório...');
290
+ await a.linkProjectToRepo(token, projectId, repositoryId);
291
+ } catch (err) {
292
+ // Vincular é cosmético (mostra o project na aba do repo) e exige `repo`
293
+ // além de `project`. Degrada para aviso em vez de derrubar o init.
294
+ return { config, warnings: [err.message] };
295
+ }
296
+ return { config, warnings: [] };
297
+ },
298
+
299
+ async verify() {
300
+ const problems = [];
301
+ const facts = {};
302
+ try {
303
+ facts.ownerType = await a.getOwnerType(token, owner);
304
+ // O GitHub App só alcança Projects v2 de ORGANIZAÇÃO. É a checagem que
305
+ // bloqueia o init antes de ele criar qualquer coisa.
306
+ if (facts.ownerType !== 'Organization') {
307
+ problems.push(`o owner "${owner}" é uma conta pessoal; Projects v2 do spec-wave exige organização`);
308
+ }
309
+ } catch (err) {
310
+ problems.push(err.message);
311
+ }
312
+ if (project?.id) {
313
+ try {
314
+ const snap = await a.getProjectSnapshot(ptk, project.id);
315
+ if (!snap) problems.push('Project não encontrado com a credencial atual');
316
+ else {
317
+ facts.projectTitle = snap.title;
318
+ facts.projectNumber = String(snap.number);
319
+ }
320
+ } catch (err) {
321
+ problems.push(err.message);
322
+ }
323
+ }
324
+ const quota = (await a.getRateLimit(ptk)) || {};
325
+ return {
326
+ ok: problems.length === 0,
327
+ quota: {
328
+ remaining: quota.remaining ?? null,
329
+ limit: quota.limit ?? null,
330
+ resetAt: quota.resetAt ?? null,
331
+ },
332
+ facts,
333
+ problems,
334
+ };
335
+ },
336
+
337
+ async createWorkItem({ title, body, tags = [], milestone = null, parent = null } = {}) {
338
+ const res = await a.createIssue(token, owner, repo, title, body, tags, {
339
+ milestone: milestone ? refNumber(milestone.key) : undefined,
340
+ });
341
+ const ref = workItemRef({ key: res.number, id: res.nodeId, url: res.url });
342
+ // Prime o memo: o database id vem de graça aqui, e é o que a API de
343
+ // dependencies exige depois. Sem isto, `decompose --apply` pagaria um
344
+ // getIssue por Story só para descobri-lo.
345
+ Object.assign(slot(ref.key), { nodeId: res.nodeId, dbId: res.id });
346
+ // `porta.addChild` e não `this.addChild`: a porta é passada adiante como
347
+ // valor e desestruturada em vários chamadores — um `this` aqui quebraria
348
+ // no primeiro `const { createWorkItem } = tracker`.
349
+ if (parent) await porta.addChild({ parent, child: ref });
350
+ return ref;
351
+ },
352
+
353
+ async getWorkItem({ ref } = {}) {
354
+ const raw = await a.getIssue(token, owner, repo, refNumber(ref));
355
+ const item = toWorkItem(raw);
356
+ if (item) Object.assign(slot(item.ref.key), { nodeId: raw.node_id, dbId: raw.id });
357
+ return item;
358
+ },
359
+
360
+ /**
361
+ * Reescreve as opções da Etapa para o vocabulário canônico do fluxo.
362
+ *
363
+ * Condicional a `boardProvisioning: 'create'`: num tracker `map-only` as
364
+ * etapas são entidades administrativas do site, e reconciliar é REMAPEAR
365
+ * (`stageMap`), não criar. Chamar isto lá seria pedir permissão de admin
366
+ * que o usuário típico não tem.
367
+ *
368
+ * ⚠️ O `id` de cada opção existente é OBRIGATÓRIO em `stages`. Sem ele o
369
+ * GitHub cria uma opção NOVA com o mesmo nome e id diferente, e todo item
370
+ * que apontava para a antiga fica sem valor, em silêncio. Quem monta a
371
+ * lista preservando os ids é `planStageSync`, no core.
372
+ *
373
+ * Devolve o schema RELIDO, para o chamador conferir a escrita em vez de
374
+ * confiar nela.
375
+ */
376
+ async syncStages({ stages = [] } = {}) {
377
+ const f = await campo('stage');
378
+ if (!f?.id) throw new Error('Campo "Etapa" não encontrado no Project — nada a sincronizar.');
379
+ await a.updateStatusField(ptk, f.id, stages);
380
+ const snap = await a.getProjectSnapshot(ptk, project.id);
381
+ return { fields: snap?.fields || {} };
382
+ },
383
+
384
+ async listWorkItemsByTag({ tag, state = 'open' } = {}) {
385
+ const octokit = new Octokit({ auth: token });
386
+ const issues = await octokit.paginate('GET /repos/{owner}/{repo}/issues', {
387
+ owner, repo, labels: tag, state, per_page: 100,
388
+ });
389
+ // A REST devolve Pull Request junto — eles são issues para a API, e não
390
+ // para o fluxo.
391
+ return issues.filter(i => !i.pull_request).map(toWorkItem);
392
+ },
393
+
394
+ async addComment({ ref, body } = {}) {
395
+ await a.commentOnIssue(token, owner, repo, refNumber(ref), body);
396
+ return null; // a API atual não devolve o comentário criado
397
+ },
398
+
399
+ async listComments({ ref } = {}) {
400
+ const cs = await a.listIssueComments(token, owner, repo, refNumber(ref));
401
+ return (cs || []).map(c => ({
402
+ id: String(c.id), body: c.body || '', author: c.author || '', createdAt: c.createdAt || '',
403
+ }));
404
+ },
405
+
406
+ updateComment({ ref: _ref, commentId, body } = {}) {
407
+ return a.updateComment(token, owner, repo, Number(commentId), body);
408
+ },
409
+
410
+ addTag({ ref, tag } = {}) {
411
+ return a.addLabel(token, owner, repo, refNumber(ref), tag);
412
+ },
413
+
414
+ removeTag({ ref, tag } = {}) {
415
+ return a.removeLabel(token, owner, repo, refNumber(ref), tag);
416
+ },
417
+
418
+ async ensureTags({ tags = [], overwrite = false, delayMs = 0, log } = {}) {
419
+ const created = [];
420
+ const updated = [];
421
+ for (let i = 0; i < tags.length; i++) {
422
+ const t = tags[i];
423
+ log?.({ index: i, total: tags.length, name: t.name });
424
+ // `overwrite` separa as duas intenções que o `update` já distingue:
425
+ // criar o que falta (idempotente — 422 de "já existe" é ignorado) e
426
+ // corrigir cor/descrição do que divergiu. Colapsar as duas faria o
427
+ // `init` começar a sobrescrever label que alguém ajustou à mão.
428
+ if (overwrite) {
429
+ await a.updateLabel(token, owner, repo, t);
430
+ updated.push(t.name);
431
+ } else {
432
+ await a.createLabel(token, owner, repo, t);
433
+ created.push(t.name);
434
+ }
435
+ // Pausa entre criações: ~30 labels em rajada trombam no rate limit
436
+ // SECUNDÁRIO do GitHub, que não devolve cabeçalho de cota — só um 403
437
+ // sem explicação. Quem decide a pausa é o chamador, porque ela depende
438
+ // do TAMANHO da rajada: o `init` cria o conjunto inteiro, o `update`
439
+ // cria as que faltam, quase sempre poucas.
440
+ if (delayMs > 0 && i < tags.length - 1) {
441
+ await new Promise(r => setTimeout(r, delayMs));
442
+ }
443
+ }
444
+ return { created, updated };
445
+ },
446
+
447
+ async listTags() {
448
+ return await a.listLabels(token, owner, repo);
449
+ },
450
+
451
+ deleteTag({ name } = {}) {
452
+ return a.deleteLabel(token, owner, repo, name);
453
+ },
454
+
455
+ countOpenWithTag({ tag } = {}) {
456
+ return a.countOpenIssuesWithLabel(token, owner, repo, tag);
457
+ },
458
+
459
+ async getStage({ ref } = {}) {
460
+ const f = await campo('stage');
461
+ if (!f?.id) return null;
462
+ return await a.getItemSingleSelectValue(ptk, await itemDoBoard(ref), f.id);
463
+ },
464
+
465
+ async setStage({ ref, stage } = {}) {
466
+ const f = await campo('stage');
467
+ if (!f?.id) return;
468
+ const opt = optionId(f, stage);
469
+ if (!opt) {
470
+ // Opção que não resolve é board divergente (coluna renomeada, init de
471
+ // outra versão). Falhar nomeando o que faltou é melhor que pular a
472
+ // escrita e devolver sucesso.
473
+ throw new Error(
474
+ `A Etapa "${stage}" não existe no board (opções: ` +
475
+ `${Object.keys(f.options || {}).join(', ') || 'nenhuma'}). ` +
476
+ 'O board divergiu da config — rode `spec-wave refresh` ou renomeie a coluna de volta.'
477
+ );
478
+ }
479
+ await a.setItemSingleSelect(ptk, project.id, await itemDoBoard(ref), f.id, opt);
480
+ },
481
+
482
+ async getProgress({ ref } = {}) {
483
+ const f = await campo('progress');
484
+ if (!f?.id) return null;
485
+ return await a.getItemSingleSelectValue(ptk, await itemDoBoard(ref), f.id);
486
+ },
487
+
488
+ async setProgress({ ref, progress } = {}) {
489
+ const f = await campo('progress');
490
+ if (!f?.id) return false;
491
+ const opt = optionId(f, progress);
492
+ if (!opt) {
493
+ throw new Error(
494
+ `O Status "${progress}" não existe no board (opções: ` +
495
+ `${Object.keys(f.options || {}).join(', ') || 'nenhuma'}).`
496
+ );
497
+ }
498
+ await a.setItemSingleSelect(ptk, project.id, await itemDoBoard(ref), f.id, opt);
499
+ return true;
500
+ },
501
+
502
+ async getField({ ref, field } = {}) {
503
+ const f = await campo(field);
504
+ if (!f?.id) return null;
505
+ return await a.getItemSingleSelectValue(ptk, await itemDoBoard(ref), f.id);
506
+ },
507
+
508
+ async setField({ ref, field, value, onlyIfEmpty = false } = {}) {
509
+ const f = await campo(field);
510
+ if (!f?.id) return false;
511
+ // Dos seis campos do RFC-001, cinco são SINGLE_SELECT e `release` é TEXT
512
+ // (config.mjs). Sem este ramo, `optionId` devolvia null num campo sem
513
+ // `options` e a escrita virava `return false` — com `release: 'native'`
514
+ // declarado nas capabilities. Ninguém percebia porque nada escreve
515
+ // `release` hoje, e o chamador não distingue "recusei" de "já estava
516
+ // preenchido": os dois são `false`.
517
+ const select = Boolean(f.options && Object.keys(f.options).length);
518
+ const opt = select ? optionId(f, value) : null;
519
+ if (select && !opt) return false;
520
+
521
+ const itemId = await itemDoBoard(ref);
522
+ if (onlyIfEmpty) {
523
+ // Escreve só no vazio: o tipo inferido do título é um palpite, e
524
+ // sobrescrever o que um humano ajustou no board trocaria dado bom por
525
+ // palpite.
526
+ const atual = select
527
+ ? await a.getItemSingleSelectValue(ptk, itemId, f.id)
528
+ : await a.getItemTextValue(ptk, itemId, f.id);
529
+ if (atual) return false;
530
+ }
531
+ if (select) await a.setItemSingleSelect(ptk, project.id, itemId, f.id, opt);
532
+ else await a.setItemText(ptk, project.id, itemId, f.id, String(value ?? ''));
533
+ return true;
534
+ },
535
+
536
+ async boardSnapshot() {
537
+ const itens = await a.listProjectItems(ptk, project.id);
538
+ return (itens || []).map(i => {
539
+ const fields = {};
540
+ let stage = null;
541
+ let progress = null;
542
+ for (const [rotulo, valor] of Object.entries(i.fields || {})) {
543
+ const canonico = FIELD_CANONICAL[rotulo];
544
+ if (canonico === 'stage') stage = valor;
545
+ else if (canonico === 'progress') progress = valor;
546
+ else if (canonico) fields[canonico] = valor;
547
+ }
548
+ // Prime o memo com o que o snapshot já trouxe: sem isto, um `setStage`
549
+ // logo depois pagaria um addProjectItem por item.
550
+ Object.assign(slot(String(i.number)), { nodeId: i.nodeId, itemId: i.itemId });
551
+ return {
552
+ ref: workItemRef({ key: i.number, id: i.nodeId }),
553
+ title: i.title || '',
554
+ state: String(i.state || '').toUpperCase() === 'CLOSED' ? 'closed' : 'open',
555
+ stage,
556
+ progress,
557
+ milestone: i.milestone ? { key: String(i.milestone.number), title: i.milestone.title } : null,
558
+ fields,
559
+ };
560
+ });
561
+ },
562
+
563
+ closeWorkItem({ ref } = {}) {
564
+ // `reason` é ignorado: no GitHub fechar é um ESTADO, e a distinção
565
+ // rejeitado × duplicata já vive nas labels (`closeSemantics: 'state'`).
566
+ return a.setIssueState(token, owner, repo, refNumber(ref), 'closed');
567
+ },
568
+
569
+ async addChild({ parent, child } = {}) {
570
+ const p = await hidratar(parent);
571
+ const c = await hidratar(child);
572
+ return await a.addSubIssue(token, p.nodeId, c.nodeId);
573
+ },
574
+
575
+ async listChildren({ ref } = {}) {
576
+ const { nodeId } = await hidratar(ref);
577
+ const filhos = await a.listSubIssues(token, nodeId);
578
+ return (filhos || []).map(f => ({
579
+ ref: workItemRef({ key: f.number, id: f.nodeId }),
580
+ title: f.title || '',
581
+ body: f.body || '',
582
+ state: f.state === 'closed' ? 'closed' : 'open',
583
+ tags: f.labels || [],
584
+ milestone: f.milestone ? { key: String(f.milestone.number), title: f.milestone.title } : null,
585
+ createdAt: f.createdAt || null,
586
+ stateReason: toStateReason(f.stateReason),
587
+ }));
588
+ },
589
+
590
+ async getParent({ ref } = {}) {
591
+ const { nodeId } = await hidratar(ref);
592
+ const p = await a.getIssueParent(token, nodeId);
593
+ if (!p) return null;
594
+ return { ref: workItemRef({ key: p.number, id: p.nodeId }), title: p.title || '' };
595
+ },
596
+
597
+ async addBlockedBy({ ref, blockedBy } = {}) {
598
+ // A API de dependencies exige o DATABASE id do bloqueador — não o number
599
+ // nem o node id. É o terceiro identificador, e é por isso que o memo existe.
600
+ const bloqueador = await hidratar(blockedBy, { need: 'db' });
601
+ return await a.addBlockedBy(token, owner, repo, refNumber(ref), bloqueador.dbId);
602
+ },
603
+
604
+ async listBlockedBy({ ref } = {}) {
605
+ const issues = await a.listBlockedBy(token, owner, repo, refNumber(ref));
606
+ return (issues || []).map(i => {
607
+ Object.assign(slot(String(i.number)), { dbId: i.id });
608
+ return {
609
+ ref: workItemRef({ key: i.number }),
610
+ title: i.title || '',
611
+ body: '',
612
+ state: i.state === 'closed' ? 'closed' : 'open',
613
+ tags: [],
614
+ milestone: null,
615
+ createdAt: null,
616
+ };
617
+ });
618
+ },
619
+
620
+ async listMilestones() {
621
+ const ms = await a.listMilestones(token, owner, repo);
622
+ return (ms || []).map(toMilestone);
623
+ },
624
+
625
+ async getMilestone({ key } = {}) {
626
+ return toMilestone(await a.getMilestone(token, owner, repo, refNumber(key)));
627
+ },
628
+
629
+ async setMilestoneDescription({ key, description } = {}) {
630
+ await a.updateMilestoneDescription(token, owner, repo, refNumber(key), description);
631
+ },
632
+
633
+ async listWorkItemsByMilestone({ milestone } = {}) {
634
+ const issues = await a.listIssuesByMilestone(token, owner, repo, refNumber(milestone.key));
635
+ return (issues || []).map(toWorkItem);
636
+ },
637
+
638
+ // `milestone: null` remove. A rota de escrita distingue os dois (ver o
639
+ // comentário em setIssueMilestone, github-rest.mjs): aqui `null` PRECISA
640
+ // chegar como null, não ser omitido.
641
+ async setMilestone({ ref, milestone = null } = {}) {
642
+ await a.setIssueMilestone(
643
+ token, owner, repo, refNumber(refKey(ref)),
644
+ milestone ? refNumber(milestone.key) : null,
645
+ );
646
+ },
647
+
648
+ async createMilestone({ title, description, dueOn = null } = {}) {
649
+ return toMilestone(await a.createMilestone(token, owner, repo, { title, description, dueOn }));
650
+ },
651
+
652
+ async updateMilestone({ key, title, description, dueOn, state } = {}) {
653
+ return toMilestone(
654
+ await a.updateMilestone(token, owner, repo, refNumber(key), { title, description, dueOn, state }),
655
+ );
656
+ },
657
+ };
658
+
659
+ return porta;
660
+ }
661
+
662
+ export { FIELD_LABEL };