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