@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
|
@@ -18,13 +18,11 @@
|
|
|
18
18
|
|
|
19
19
|
import { execSync } from 'node:child_process';
|
|
20
20
|
import { resolveToken } from '../api/auth.mjs';
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
getRepoDefaultBranch,
|
|
24
|
-
} from '../api/github-rest.mjs';
|
|
21
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
22
|
+
import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
|
|
25
23
|
import { codeRepositories, repoLabel, repoLabelSpec } from '../lib/repo-role.mjs';
|
|
26
|
-
|
|
27
|
-
import {
|
|
24
|
+
|
|
25
|
+
import { openTracker, advanceToStage } from '../lib/board.mjs';
|
|
28
26
|
import { generateDocument } from '../lib/claude.mjs';
|
|
29
27
|
import {
|
|
30
28
|
runCritique, resolveCritiqueAttempt, renderNeedsHumanComment,
|
|
@@ -45,6 +43,7 @@ import { loadArtifact } from '../lib/doc-source.mjs';
|
|
|
45
43
|
import { awaitingMergeBlock } from '../lib/artifact-pr.mjs';
|
|
46
44
|
import { isAwaitingMerge } from '../lib/doc-source.mjs';
|
|
47
45
|
import { loadPrompt, systemPromptWithTools } from '../lib/prompt-loader.mjs';
|
|
46
|
+
import { cliRef } from '../lib/cli-ref.mjs';
|
|
48
47
|
import {
|
|
49
48
|
renderDecompositionDoc, parseDecompositionDoc, DECOMPOSITION_FILE,
|
|
50
49
|
} from '../lib/decomposition-doc.mjs';
|
|
@@ -60,12 +59,15 @@ import {
|
|
|
60
59
|
// `itemType` é o tipo do que ACABOU de ser criado ('Story'/'Task'/'Feature') —
|
|
61
60
|
// aqui não há dúvida sobre ele, e sem essa passagem o Work Item Type das issues
|
|
62
61
|
// nascidas do apply ficava vazio para sempre (ver ensureWorkItemType).
|
|
63
|
-
async function moveToReady(
|
|
64
|
-
if (!
|
|
65
|
-
await advanceToStage(
|
|
66
|
-
|
|
67
|
-
{
|
|
68
|
-
|
|
62
|
+
async function moveToReady(board, number, nodeId, itemType) {
|
|
63
|
+
if (!board?.tracker) return;
|
|
64
|
+
await advanceToStage({
|
|
65
|
+
tracker: board.tracker,
|
|
66
|
+
ref: { key: String(number), id: nodeId },
|
|
67
|
+
stage: STAGE_READY,
|
|
68
|
+
progress: PROGRESS_TODO,
|
|
69
|
+
itemType,
|
|
70
|
+
});
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
/**
|
|
@@ -213,7 +215,10 @@ export function shouldSkipDecompose({ labels = [], subIssues = [], type } = {})
|
|
|
213
215
|
if (prefix) {
|
|
214
216
|
const existing = subIssues.find(s => (s.title || '').includes(prefix));
|
|
215
217
|
if (existing) {
|
|
216
|
-
|
|
218
|
+
// `subIssues` vem de `listChildren`, onde a chave mora em `ref`. Lido
|
|
219
|
+
// cru, o ternário engolia o exemplo e a recusa perdia o "(ex.: #N)".
|
|
220
|
+
const n = existing.ref?.key ?? existing.number;
|
|
221
|
+
const ref = n ? ` (ex.: #${n} — ${existing.title})` : '';
|
|
217
222
|
return { skip: true, reason: `a issue já tem sub-issues \`${prefix}\`${ref}` };
|
|
218
223
|
}
|
|
219
224
|
}
|
|
@@ -267,7 +272,10 @@ async function publishFile(ctx, { doc, pathRel, content, nextLabel = null, extra
|
|
|
267
272
|
token, owner, repo, doc,
|
|
268
273
|
issueNumber: parseInt(issueNumber, 10),
|
|
269
274
|
issueTitle: issue?.title || '',
|
|
270
|
-
|
|
275
|
+
// `ref.url`, como os outros quatro chamadores de publishArtifact: o
|
|
276
|
+
// WorkItem da porta não tem `html_url`, e uma URL vazia deixa o corpo do PR
|
|
277
|
+
// de artefato com `- Issue: — Título`, sem link nenhum.
|
|
278
|
+
issueUrl: issue?.ref?.url || issue?.html_url || '',
|
|
271
279
|
pathRel, content, base, nextLabel, extraFiles,
|
|
272
280
|
});
|
|
273
281
|
if (published.warning) console.warn(`⚠️ ${published.warning}`);
|
|
@@ -302,7 +310,7 @@ export function codeReposPromptSection(config) {
|
|
|
302
310
|
|
|
303
311
|
async function draftDecomposition(ctx) {
|
|
304
312
|
const {
|
|
305
|
-
token, owner, repo, issue, issueNumber, type, labels, usage, root, runMode,
|
|
313
|
+
token, owner, repo, tracker, issue, issueNumber, type, labels, usage, root, runMode,
|
|
306
314
|
docRel, dirRel, base,
|
|
307
315
|
} = ctx;
|
|
308
316
|
const number = parseInt(issueNumber, 10);
|
|
@@ -322,11 +330,13 @@ async function draftDecomposition(ctx) {
|
|
|
322
330
|
const bloqueio = awaitingMergeBlock({
|
|
323
331
|
pathRel: `${dirRel}/${nome}`, state: doc.state, pr: doc.pr, branch: doc.ref,
|
|
324
332
|
});
|
|
325
|
-
await
|
|
326
|
-
await
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
333
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE }).catch(() => {});
|
|
334
|
+
await tracker.addComment({
|
|
335
|
+
ref: { key: String(number) },
|
|
336
|
+
body:
|
|
337
|
+
`⏸️ **decompose parado:** ${bloqueio.message}\n\n${bloqueio.unblock}\n\n` +
|
|
338
|
+
`Reaplique \`${LABEL_DECOMPOSE}\` depois do merge.`,
|
|
339
|
+
}).catch(() => {});
|
|
330
340
|
throw new DecomposeBlockedError(bloqueio.message);
|
|
331
341
|
}
|
|
332
342
|
}
|
|
@@ -417,13 +427,15 @@ async function draftDecomposition(ctx) {
|
|
|
417
427
|
try {
|
|
418
428
|
doc = parseDecompositionDoc(markdown);
|
|
419
429
|
} catch (err) {
|
|
420
|
-
await
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
430
|
+
await tracker.addComment({
|
|
431
|
+
ref: { key: String(number) },
|
|
432
|
+
body:
|
|
433
|
+
`❌ **Não consegui ler o rascunho da decomposição.**\n\n` +
|
|
434
|
+
`\`\`\`\n${err.message}\n\`\`\`\n\n` +
|
|
435
|
+
`Corrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_DECOMPOSE}\`. ` +
|
|
436
|
+
`Para começar de novo do zero, apague o arquivo.`,
|
|
437
|
+
}).catch(() => {});
|
|
438
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE }).catch(() => {});
|
|
427
439
|
throw new DecomposeBlockedError(err.message);
|
|
428
440
|
}
|
|
429
441
|
const itemCount = kind === 'stories'
|
|
@@ -444,14 +456,18 @@ async function draftDecomposition(ctx) {
|
|
|
444
456
|
const decisions = parseCritiqueDecisions(ctx.comments, 'stories');
|
|
445
457
|
if (blocked) {
|
|
446
458
|
console.log(`Teto de ${ctx.maxCritiqueAttempts} tentativas de crítica atingido — exigindo revisão humana.`);
|
|
447
|
-
await
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
459
|
+
await tracker.addComment({
|
|
460
|
+
ref: { key: String(number) },
|
|
461
|
+
body:
|
|
462
|
+
renderNeedsHumanComment({
|
|
463
|
+
kind: 'stories',
|
|
464
|
+
attempt,
|
|
465
|
+
maxAttempts: ctx.maxCritiqueAttempts,
|
|
466
|
+
escalationModel: ctx.escalationModel,
|
|
467
|
+
}),
|
|
468
|
+
}).catch(() => {});
|
|
469
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_NEEDS_HUMAN });
|
|
470
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE });
|
|
455
471
|
throw new DecomposeBlockedError(
|
|
456
472
|
`A crítica reprovou ${ctx.maxCritiqueAttempts - 1}x seguidas. Label ${LABEL_NEEDS_HUMAN} ` +
|
|
457
473
|
'aplicada: o fluxo exige revisão humana antes de continuar.'
|
|
@@ -480,18 +496,20 @@ async function draftDecomposition(ctx) {
|
|
|
480
496
|
// A crítica é o portão que impede stories contraditórias de virarem trabalho.
|
|
481
497
|
// Liberar o rascunho com o portão comprovadamente não executado é exatamente
|
|
482
498
|
// o que se quer evitar — então aborta, e a Action fica vermelha.
|
|
483
|
-
await
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
499
|
+
await tracker.addComment({
|
|
500
|
+
ref: { key: String(number) },
|
|
501
|
+
body:
|
|
502
|
+
`❌ **A crítica adversarial não concluiu.**\n\n` +
|
|
503
|
+
`\`\`\`\n${err.message}\n\`\`\`\n\n` +
|
|
504
|
+
`O rascunho está commitado em [\`${docRel}\`](${blobUrl}), mas **nada foi criado** — ` +
|
|
505
|
+
`sem crítica não há garantia de que as Stories respeitam a spec. ` +
|
|
506
|
+
`Reaplique \`${LABEL_DECOMPOSE}\` para tentar de novo.`,
|
|
507
|
+
}).catch(() => {});
|
|
508
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE }).catch(() => {});
|
|
491
509
|
throw new DecomposeBlockedError(`Crítica adversarial não concluiu: ${err.message}`);
|
|
492
510
|
}
|
|
493
511
|
|
|
494
|
-
await
|
|
512
|
+
await tracker.addComment({ ref: { key: String(number) }, body: critique.markdown })
|
|
495
513
|
.catch(err => console.warn(`Falha ao comentar a crítica: ${err.message}`));
|
|
496
514
|
|
|
497
515
|
// Graves SEM decisão do TL. É este o portão que travava a #18: com spec e
|
|
@@ -499,15 +517,14 @@ async function draftDecomposition(ctx) {
|
|
|
499
517
|
// um documento está certo, ou aceitar o risco, item a item.
|
|
500
518
|
const { blocking, accepted } = applyCritiqueDecisions(critique.findings, decisions, 'stories');
|
|
501
519
|
if (accepted.length > 0) {
|
|
502
|
-
await
|
|
503
|
-
await
|
|
504
|
-
renderRiskAcceptedComment({ kind: 'stories', accepted })).catch(() => {});
|
|
520
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_RISK_ACCEPTED }).catch(() => {});
|
|
521
|
+
await tracker.addComment({ ref: { key: String(number) }, body: renderRiskAcceptedComment({ kind: 'stories', accepted }) }).catch(() => {});
|
|
505
522
|
}
|
|
506
523
|
if (blocking.length > 0) {
|
|
507
524
|
console.log(`Crítica adversarial apontou ${blocking.length} finding(s) GRAVE(s) sem decisão — nenhum item foi criado.`);
|
|
508
|
-
await
|
|
509
|
-
await
|
|
510
|
-
await
|
|
525
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_CRITIQUE_FAILED });
|
|
526
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_READY }).catch(() => {});
|
|
527
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE });
|
|
511
528
|
throw new DecomposeBlockedError(
|
|
512
529
|
`A crítica adversarial apontou findings graves no rascunho (tentativa ${attempt}). ` +
|
|
513
530
|
`Nenhuma issue foi criada. Corrija ${docRel} e reaplique ${LABEL_DECOMPOSE}.`
|
|
@@ -516,17 +533,17 @@ async function draftDecomposition(ctx) {
|
|
|
516
533
|
|
|
517
534
|
// Crítica limpa: remove o bloqueio anterior, que também zera o contador de
|
|
518
535
|
// tentativas na próxima rodada (ver resolveCritiqueAttempt).
|
|
519
|
-
await
|
|
536
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_CRITIQUE_FAILED }).catch(() => {});
|
|
520
537
|
return await finishDraft(ctx, { doc, blobUrl, itemCount, critiqued: true, publicado });
|
|
521
538
|
}
|
|
522
539
|
|
|
523
540
|
// Fecho comum do rascunho aprovado: libera para revisão humana e o apply.
|
|
524
541
|
async function finishDraft(
|
|
525
|
-
{
|
|
542
|
+
{ tracker, issueNumber, docRel }, { blobUrl, itemCount, critiqued, publicado }
|
|
526
543
|
) {
|
|
527
544
|
const number = parseInt(issueNumber, 10);
|
|
528
|
-
await
|
|
529
|
-
await
|
|
545
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_READY });
|
|
546
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE });
|
|
530
547
|
|
|
531
548
|
// O apply LÊ o rascunho da branch base, então ele só roda depois do merge —
|
|
532
549
|
// dizer "crie as issues agora" sem essa ressalva manda o humano num passo que
|
|
@@ -538,18 +555,20 @@ async function finishDraft(
|
|
|
538
555
|
'faça o merge e então crie as issues:\n'
|
|
539
556
|
: '**Nada foi criado ainda.** Revise (e edite, se quiser) o arquivo e então crie as issues:\n';
|
|
540
557
|
|
|
541
|
-
await
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
558
|
+
await tracker.addComment({
|
|
559
|
+
ref: { key: String(number) },
|
|
560
|
+
body:
|
|
561
|
+
`📝 **Rascunho de decomposição pronto para revisão** (${itemCount}).\n\n` +
|
|
562
|
+
`📄 Arquivo: [\`${docRel}\`](${blobUrl})\n\n` +
|
|
563
|
+
(critiqued
|
|
564
|
+
? 'A crítica adversarial não encontrou contradições graves. '
|
|
565
|
+
: '') +
|
|
566
|
+
revisao +
|
|
567
|
+
`\`\`\`\ngh issue edit ${issueNumber} --add-label "${LABEL_DECOMPOSE_APPLY}"\n\`\`\`\n` +
|
|
568
|
+
`Se preferir uma nova crítica depois de editar, reaplique \`${LABEL_DECOMPOSE}\` — ` +
|
|
569
|
+
'o arquivo é criticado como está, sem ser regerado. Para gerar outro do zero, ' +
|
|
570
|
+
'feche o PR e apague a branch.',
|
|
571
|
+
}).catch(err => console.warn(`Falha ao comentar o rascunho: ${err.message}`));
|
|
553
572
|
console.log(`Rascunho liberado para revisão: ${itemCount}.`);
|
|
554
573
|
return { pr: pr || null };
|
|
555
574
|
}
|
|
@@ -559,7 +578,7 @@ async function finishDraft(
|
|
|
559
578
|
// ---------------------------------------------------------------------------
|
|
560
579
|
|
|
561
580
|
async function applyDecomposition(ctx) {
|
|
562
|
-
const { token, owner, repo, issueNumber, docRel, root, base } = ctx;
|
|
581
|
+
const { token, owner, repo, tracker, issueNumber, docRel, root, base } = ctx;
|
|
563
582
|
const number = parseInt(issueNumber, 10);
|
|
564
583
|
|
|
565
584
|
const rascunho = await loadArtifact({
|
|
@@ -578,21 +597,25 @@ async function applyDecomposition(ctx) {
|
|
|
578
597
|
const bloqueio = awaitingMergeBlock({
|
|
579
598
|
pathRel: docRel, state: rascunho.state, pr: rascunho.pr, branch: rascunho.ref,
|
|
580
599
|
});
|
|
581
|
-
await
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
600
|
+
await tracker.addComment({
|
|
601
|
+
ref: { key: String(number) },
|
|
602
|
+
body:
|
|
603
|
+
`⏸️ **decompose-apply parado:** ${bloqueio.message}\n\n${bloqueio.unblock}\n\n` +
|
|
604
|
+
`Nenhuma issue foi criada. Reaplique \`${LABEL_DECOMPOSE_APPLY}\` depois do merge.`,
|
|
605
|
+
}).catch(() => {});
|
|
606
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_APPLY }).catch(() => {});
|
|
586
607
|
throw new DecomposeBlockedError(bloqueio.message);
|
|
587
608
|
}
|
|
588
609
|
|
|
589
610
|
if (rascunho.content == null) {
|
|
590
|
-
await
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
611
|
+
await tracker.addComment({
|
|
612
|
+
ref: { key: String(number) },
|
|
613
|
+
body:
|
|
614
|
+
`❌ **Não há rascunho de decomposição para aplicar.**\n\n` +
|
|
615
|
+
`Esperava encontrar \`${docRel}\`. Gere o rascunho primeiro:\n` +
|
|
616
|
+
`\`\`\`\ngh issue edit ${issueNumber} --add-label "${LABEL_DECOMPOSE}"\n\`\`\`\n`,
|
|
617
|
+
}).catch(() => {});
|
|
618
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_APPLY }).catch(() => {});
|
|
596
619
|
throw new DecomposeBlockedError(`${docRel} não encontrado — aplique ${LABEL_DECOMPOSE} primeiro.`);
|
|
597
620
|
}
|
|
598
621
|
|
|
@@ -600,12 +623,14 @@ async function applyDecomposition(ctx) {
|
|
|
600
623
|
try {
|
|
601
624
|
doc = parseDecompositionDoc(rascunho.content);
|
|
602
625
|
} catch (err) {
|
|
603
|
-
await
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
626
|
+
await tracker.addComment({
|
|
627
|
+
ref: { key: String(number) },
|
|
628
|
+
body:
|
|
629
|
+
`❌ **Não consegui ler o rascunho da decomposição.**\n\n` +
|
|
630
|
+
`\`\`\`\n${err.message}\n\`\`\`\n\n` +
|
|
631
|
+
`Corrija \`${docRel}\` e reaplique \`${LABEL_DECOMPOSE_APPLY}\`.`,
|
|
632
|
+
}).catch(() => {});
|
|
633
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_APPLY }).catch(() => {});
|
|
609
634
|
throw new DecomposeBlockedError(err.message);
|
|
610
635
|
}
|
|
611
636
|
|
|
@@ -621,8 +646,8 @@ async function applyDecomposition(ctx) {
|
|
|
621
646
|
|
|
622
647
|
// Campos do board só são resolvidos aqui: a etapa de rascunho não toca o board.
|
|
623
648
|
// `strict`: no apply, board inalcançável ABORTA antes da primeira criação.
|
|
624
|
-
const
|
|
625
|
-
const applyCtx = { ...ctx,
|
|
649
|
+
const board = await resolveBoard(ctx, { strict: true });
|
|
650
|
+
const applyCtx = { ...ctx, board };
|
|
626
651
|
|
|
627
652
|
// As falhas de board voltam em vez de subir na hora: a exceção precisa esperar
|
|
628
653
|
// a contabilidade de labels abaixo. Lançar aqui deixaria o gatilho
|
|
@@ -686,19 +711,19 @@ async function applyDecomposition(ctx) {
|
|
|
686
711
|
// mentiria por até um TTL inteiro.
|
|
687
712
|
invalidateCache(ctx.root, `subissues-${number}`, 'board-items');
|
|
688
713
|
|
|
689
|
-
await
|
|
714
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSED })
|
|
690
715
|
.catch(err => console.warn(`Falha ao aplicar a label ${LABEL_DECOMPOSED}: ${err.message}`));
|
|
691
716
|
// Best-effort como as duas vizinhas: as issues já existem, e derrubar o run
|
|
692
717
|
// porque a REMOÇÃO de uma label falhou (404 de label já removida por um run
|
|
693
718
|
// concorrente, 5xx da API) transformava um apply concluído em vermelho — e o
|
|
694
719
|
// vermelho manda o humano reaplicar o gatilho, que é o caminho para duplicar
|
|
695
720
|
// dezenas de issues. A label que sobra é visível na issue e removível à mão.
|
|
696
|
-
await
|
|
721
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_APPLY })
|
|
697
722
|
.catch(err => console.warn(
|
|
698
723
|
`Decomposição aplicada, mas a label ${LABEL_DECOMPOSE_APPLY} não pôde ser removida ` +
|
|
699
724
|
`(${err.message}). Remova-a à mão: gh issue edit ${number} --remove-label "${LABEL_DECOMPOSE_APPLY}".`
|
|
700
725
|
));
|
|
701
|
-
await
|
|
726
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_READY }).catch(() => {});
|
|
702
727
|
|
|
703
728
|
// Por último, com as labels já consistentes: escrita de board incompleta
|
|
704
729
|
// termina o run em VERMELHO.
|
|
@@ -721,7 +746,7 @@ export function renderBoardFailures(failures) {
|
|
|
721
746
|
`${linhas}\n\n` +
|
|
722
747
|
`Motivo: \`${motivo}\`\n\n` +
|
|
723
748
|
'Verifique o `GH_PROJECT_TOKEN` (scope `project` e acesso ao Project da organização) e ' +
|
|
724
|
-
|
|
749
|
+
`reposicione os itens com \`npx ${cliRef()} repair-stage <issue>\`.\n\n` +
|
|
725
750
|
'O run termina em VERMELHO de propósito — a decomposição em si CONCLUIU. ' +
|
|
726
751
|
`Não reaplique \`${LABEL_DECOMPOSE_APPLY}\`: as issues acima já existem e o apply ` +
|
|
727
752
|
'recomeça do zero; o que falta é só a Etapa, e quem repara isso é o `repair-stage`.'
|
|
@@ -765,7 +790,7 @@ function milestoneLine(issue, milestone) {
|
|
|
765
790
|
*
|
|
766
791
|
* @returns {Promise<Map<number, {number:number, id:number, title:string}>>}
|
|
767
792
|
*/
|
|
768
|
-
async function resolveExternalDeps({
|
|
793
|
+
async function resolveExternalDeps({ tracker }, doc) {
|
|
769
794
|
const numeros = [...new Set(
|
|
770
795
|
(doc.stories || []).flatMap(s => s.dependsOnIssues || [])
|
|
771
796
|
)].sort((a, b) => a - b);
|
|
@@ -773,8 +798,10 @@ async function resolveExternalDeps({ token, owner, repo }, doc) {
|
|
|
773
798
|
const faltando = [];
|
|
774
799
|
for (const n of numeros) {
|
|
775
800
|
try {
|
|
776
|
-
const
|
|
777
|
-
|
|
801
|
+
const dep = await tracker.getWorkItem({ ref: { key: String(n) } });
|
|
802
|
+
// `ref` viaja junto: é ele que `addBlockedBy` consome, e é lá que o
|
|
803
|
+
// plugin acha o database id sem pagar um getIssue a mais.
|
|
804
|
+
resolvidas.set(n, { number: Number(dep.ref.key), ref: dep.ref, title: dep.title });
|
|
778
805
|
} catch (err) {
|
|
779
806
|
faltando.push(`#${n} (${err.status === 404 ? 'não existe' : err.message})`);
|
|
780
807
|
}
|
|
@@ -801,7 +828,7 @@ async function resolveExternalDeps({ token, owner, repo }, doc) {
|
|
|
801
828
|
*
|
|
802
829
|
* @returns {Promise<Map<string, string[]>>} anchor da Story → labels
|
|
803
830
|
*/
|
|
804
|
-
async function resolveRepoLabels({
|
|
831
|
+
async function resolveRepoLabels({ tracker, config }, doc) {
|
|
805
832
|
const porStory = new Map();
|
|
806
833
|
const slugs = [...new Set((doc.stories || []).flatMap(s => s.repos || []))].sort();
|
|
807
834
|
if (slugs.length === 0) return porStory;
|
|
@@ -821,7 +848,7 @@ async function resolveRepoLabels({ token, owner, repo, config }, doc) {
|
|
|
821
848
|
const spec = repoLabelSpec(slug);
|
|
822
849
|
try {
|
|
823
850
|
// createLabel já engole o 422 de "já existe".
|
|
824
|
-
await
|
|
851
|
+
await tracker.ensureTags({ tags: [spec] });
|
|
825
852
|
} catch (err) {
|
|
826
853
|
console.warn(` Não consegui garantir a label ${spec.name}: ${err.message}`);
|
|
827
854
|
}
|
|
@@ -833,9 +860,8 @@ async function resolveRepoLabels({ token, owner, repo, config }, doc) {
|
|
|
833
860
|
}
|
|
834
861
|
|
|
835
862
|
async function createStoriesFromDoc(ctx, doc) {
|
|
836
|
-
const { token,
|
|
837
|
-
const
|
|
838
|
-
const featureNodeId = issue.node_id;
|
|
863
|
+
const { token, owner, repo, tracker, issue, issueNumber, board, docRel } = ctx;
|
|
864
|
+
const featureNodeId = issue.ref.id;
|
|
839
865
|
// Herdado uma vez e reusado por todas as Stories e Tasks deste apply.
|
|
840
866
|
const milestone = resolveInheritedMilestone(issue);
|
|
841
867
|
if (milestone) console.log(`Milestone herdado da ${ctx.type}: ${issue.milestone?.title ?? `#${milestone}`}.`);
|
|
@@ -866,17 +892,25 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
866
892
|
...story.dependsOn.map(idx => createdStories[idx]),
|
|
867
893
|
...(story.dependsOnIssues || []).map(n => externas.get(n)),
|
|
868
894
|
].filter(Boolean);
|
|
869
|
-
|
|
895
|
+
// `depIssues` mistura duas formas: Story recém-criada é um `WorkItemRef`
|
|
896
|
+
// (tem `key`), e dependência externa vem de `resolveExternalDeps` (tem
|
|
897
|
+
// `number`). Ler só uma delas grava `Depende de: #undefined` no corpo.
|
|
898
|
+
const depNumero = d => Number(d.key ?? d.number);
|
|
899
|
+
const depLine = formatDependencyLine(depIssues.map(depNumero));
|
|
870
900
|
if (depLine) storyBody += `\n\n${depLine}`;
|
|
871
901
|
|
|
872
902
|
// `repo:<slug>` já na criação (RFC-005 §6.2 item 6) — a label é a fonte de
|
|
873
903
|
// verdade de quais repositórios a Story toca; o campo do board é só espelho.
|
|
874
904
|
const labelsDoRepo = repoLabels.get(story.anchor) || [];
|
|
875
|
-
const createdStory = await
|
|
876
|
-
|
|
905
|
+
const createdStory = await tracker.createWorkItem({
|
|
906
|
+
title: storyTitle, body: storyBody, type: 'Story',
|
|
907
|
+
tags: ['[STORY]', ...labelsDoRepo],
|
|
908
|
+
milestone: milestone ? { key: String(milestone) } : null,
|
|
909
|
+
});
|
|
910
|
+
ctx.createdItems.push(createdStory.key);
|
|
877
911
|
// Anota no doc em memória: é daqui que sai o `**Issue:** #N` gravado no
|
|
878
912
|
// arquivo no fim do apply.
|
|
879
|
-
story.issue = createdStory.
|
|
913
|
+
story.issue = createdStory.key;
|
|
880
914
|
created.push({ title: storyTitle, url: createdStory.url });
|
|
881
915
|
createdStories.push(createdStory);
|
|
882
916
|
generatedTexts.push(storyTitle, storyBody);
|
|
@@ -884,22 +918,22 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
884
918
|
// Relação nativa blocked_by (best-effort — a linha "Depende de" já basta).
|
|
885
919
|
for (const dep of depIssues) {
|
|
886
920
|
try {
|
|
887
|
-
await addBlockedBy(
|
|
921
|
+
await tracker.addBlockedBy({ ref: createdStory, blockedBy: dep.ref ?? dep });
|
|
888
922
|
} catch (err) {
|
|
889
|
-
console.warn(` Falha ao marcar story #${createdStory.
|
|
923
|
+
console.warn(` Falha ao marcar story #${createdStory.key} como bloqueada por #${depNumero(dep)}: ${err.message}`);
|
|
890
924
|
}
|
|
891
925
|
}
|
|
892
926
|
|
|
893
927
|
try {
|
|
894
|
-
await
|
|
928
|
+
await tracker.addChild({ parent: { key: String(issueNumber), id: featureNodeId }, child: createdStory });
|
|
895
929
|
} catch (err) {
|
|
896
|
-
console.warn(` Story #${createdStory.
|
|
930
|
+
console.warn(` Story #${createdStory.key} criada, mas falhou ao vincular à Feature: ${err.message}`);
|
|
897
931
|
}
|
|
898
932
|
try {
|
|
899
|
-
await moveToReady(
|
|
933
|
+
await moveToReady(board, createdStory.key, createdStory.id, 'Story');
|
|
900
934
|
} catch (err) {
|
|
901
|
-
console.warn(` Falha ao mover story #${createdStory.
|
|
902
|
-
boardFailures.push({ number: createdStory.
|
|
935
|
+
console.warn(` Falha ao mover story #${createdStory.key} para "${STAGE_READY}": ${err.message}`);
|
|
936
|
+
boardFailures.push({ number: createdStory.key, kind: 'Story', reason: err.message });
|
|
903
937
|
}
|
|
904
938
|
|
|
905
939
|
for (const task of story.tasks || []) {
|
|
@@ -908,27 +942,31 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
908
942
|
const taskBody = `${task.body}\n\n_Story pai: ${createdStory.url}_`;
|
|
909
943
|
// A Task herda os repos da Story (RFC-005 §5.2, `effectiveRepoSlugs`) —
|
|
910
944
|
// gravado na label em vez de inferido, para `order`/`implement` lerem direto.
|
|
911
|
-
const createdTask = await
|
|
912
|
-
|
|
913
|
-
|
|
945
|
+
const createdTask = await tracker.createWorkItem({
|
|
946
|
+
title: taskTitle, body: taskBody, type: 'Task',
|
|
947
|
+
tags: ['[TASK]', ...labelsDoRepo],
|
|
948
|
+
milestone: milestone ? { key: String(milestone) } : null,
|
|
949
|
+
});
|
|
950
|
+
ctx.createdItems.push(createdTask.key);
|
|
951
|
+
task.issue = createdTask.key;
|
|
914
952
|
generatedTexts.push(taskTitle, taskBody);
|
|
915
953
|
try {
|
|
916
|
-
await
|
|
954
|
+
await tracker.addChild({ parent: createdStory, child: createdTask });
|
|
917
955
|
} catch (err) {
|
|
918
|
-
console.warn(` Task #${createdTask.
|
|
956
|
+
console.warn(` Task #${createdTask.key} criada, mas falhou ao vincular à Story: ${err.message}`);
|
|
919
957
|
}
|
|
920
958
|
try {
|
|
921
|
-
await moveToReady(
|
|
959
|
+
await moveToReady(board, createdTask.key, createdTask.id, 'Task');
|
|
922
960
|
} catch (err) {
|
|
923
|
-
console.warn(` Falha ao mover task #${createdTask.
|
|
924
|
-
boardFailures.push({ number: createdTask.
|
|
961
|
+
console.warn(` Falha ao mover task #${createdTask.key} para "${STAGE_READY}": ${err.message}`);
|
|
962
|
+
boardFailures.push({ number: createdTask.key, kind: 'Task', reason: err.message });
|
|
925
963
|
}
|
|
926
964
|
}
|
|
927
965
|
}
|
|
928
966
|
|
|
929
967
|
try {
|
|
930
|
-
await moveToReady(
|
|
931
|
-
if (
|
|
968
|
+
await moveToReady(board, issueNumber, featureNodeId, ctx.type);
|
|
969
|
+
if (board?.tracker) console.log(`Feature movida para "${STAGE_READY}" no board.`);
|
|
932
970
|
} catch (err) {
|
|
933
971
|
console.warn(`Falha ao mover Feature para "${STAGE_READY}": ${err.message}`);
|
|
934
972
|
boardFailures.push({ number: parseInt(issueNumber, 10), kind: 'Feature', reason: err.message });
|
|
@@ -936,17 +974,19 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
936
974
|
|
|
937
975
|
const list = created.map(s => `- ${s.url} — ${s.title}`).join('\n');
|
|
938
976
|
const posicionamento = boardFailures.length === 0
|
|
939
|
-
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx
|
|
977
|
+
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx ${cliRef()} implement ${issueNumber}\` (Stories em ordem de dependência).`
|
|
940
978
|
: renderBoardFailures(boardFailures);
|
|
941
|
-
await
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
979
|
+
await tracker.addComment({
|
|
980
|
+
ref: { key: String(parseInt(issueNumber, 10)) },
|
|
981
|
+
body:
|
|
982
|
+
`🔀 **Decomposição aplicada!**\n\n` +
|
|
983
|
+
`A partir de \`${docRel}\` foram criados ${created.length} stories e suas tasks:\n\n${list}\n\n` +
|
|
984
|
+
milestoneLine(issue, milestone) +
|
|
985
|
+
posicionamento +
|
|
986
|
+
formatItemsLintWarning(generatedTexts),
|
|
987
|
+
}).catch(err => console.warn(`Falha ao comentar a decomposição: ${err.message}`));
|
|
988
|
+
|
|
989
|
+
await commentStoryOrder({ tracker, issueNumber, doc, createdStories });
|
|
950
990
|
|
|
951
991
|
console.log(`Decomposição aplicada: ${created.length} stories criadas.`);
|
|
952
992
|
return boardFailures;
|
|
@@ -964,18 +1004,18 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
964
1004
|
* BEST-EFFORT, como o comentário que o antecede: a decomposição está feita e
|
|
965
1005
|
* paga, e falhar ao comentar não pode desfazê-la nem mascarar o que deu certo.
|
|
966
1006
|
*/
|
|
967
|
-
async function commentStoryOrder({
|
|
1007
|
+
async function commentStoryOrder({ tracker, issueNumber, doc, createdStories }) {
|
|
968
1008
|
try {
|
|
969
1009
|
const stories = doc.stories
|
|
970
1010
|
.map((story, i) => {
|
|
971
1011
|
const criada = createdStories[i];
|
|
972
1012
|
if (!criada) return null; // criação falhou no meio: não inventa a Story
|
|
973
1013
|
return {
|
|
974
|
-
number: criada.
|
|
1014
|
+
number: Number(criada.key),
|
|
975
1015
|
title: story.title,
|
|
976
1016
|
// dependsOn vem 0-based (índice no doc) e vira número de issue.
|
|
977
1017
|
dependsOn: (story.dependsOn || [])
|
|
978
|
-
.map(idx => createdStories[idx]
|
|
1018
|
+
.map(idx => createdStories[idx] && Number(createdStories[idx].key))
|
|
979
1019
|
.filter(Boolean),
|
|
980
1020
|
};
|
|
981
1021
|
})
|
|
@@ -988,8 +1028,7 @@ async function commentStoryOrder({ token, owner, repo, issueNumber, doc, created
|
|
|
988
1028
|
stories.map(({ number, dependsOn }) => ({ number, dependsOn }))
|
|
989
1029
|
);
|
|
990
1030
|
|
|
991
|
-
await
|
|
992
|
-
renderOrderComment({ sorted, cycle, byNumber }));
|
|
1031
|
+
await tracker.addComment({ ref: { key: String(parseInt(issueNumber, 10)) }, body: renderOrderComment({ sorted, cycle, byNumber }) });
|
|
993
1032
|
console.log(`Ordem de execução comentada: ${sorted.length} story(ies).`);
|
|
994
1033
|
} catch (err) {
|
|
995
1034
|
console.warn(`Falha ao comentar a ordem de execução: ${err.message}`);
|
|
@@ -997,9 +1036,8 @@ async function commentStoryOrder({ token, owner, repo, issueNumber, doc, created
|
|
|
997
1036
|
}
|
|
998
1037
|
|
|
999
1038
|
async function createTasksFromDoc(ctx, doc) {
|
|
1000
|
-
const { token,
|
|
1001
|
-
const
|
|
1002
|
-
const parentNodeId = issue.node_id;
|
|
1039
|
+
const { token, owner, repo, tracker, issue, issueNumber, board, docRel } = ctx;
|
|
1040
|
+
const parentNodeId = issue.ref.id;
|
|
1003
1041
|
const milestone = resolveInheritedMilestone(issue);
|
|
1004
1042
|
if (milestone) console.log(`Milestone herdado do RFC: ${issue.milestone?.title ?? `#${milestone}`}.`);
|
|
1005
1043
|
const created = [];
|
|
@@ -1009,94 +1047,83 @@ async function createTasksFromDoc(ctx, doc) {
|
|
|
1009
1047
|
for (const task of doc.tasks) {
|
|
1010
1048
|
console.log(`Criando task: ${task.title}`);
|
|
1011
1049
|
const taskTitle = `[TASK] ${task.title}`;
|
|
1012
|
-
const taskBody = `${task.body}\n\n_RFC pai: ${issue.html_url || `#${issueNumber}`}_`;
|
|
1013
|
-
const createdTask = await
|
|
1014
|
-
|
|
1015
|
-
|
|
1050
|
+
const taskBody = `${task.body}\n\n_RFC pai: ${issue.ref?.url || issue.html_url || `#${issueNumber}`}_`;
|
|
1051
|
+
const createdTask = await tracker.createWorkItem({
|
|
1052
|
+
title: taskTitle, body: taskBody, type: 'Task', tags: ['[TASK]'],
|
|
1053
|
+
milestone: milestone ? { key: String(milestone) } : null,
|
|
1054
|
+
});
|
|
1055
|
+
ctx.createdItems.push(createdTask.key);
|
|
1056
|
+
task.issue = createdTask.key;
|
|
1016
1057
|
created.push({ title: taskTitle, url: createdTask.url });
|
|
1017
1058
|
generatedTexts.push(taskTitle, taskBody);
|
|
1018
1059
|
|
|
1019
1060
|
try {
|
|
1020
|
-
await
|
|
1061
|
+
await tracker.addChild({ parent: { key: String(issueNumber), id: parentNodeId }, child: createdTask });
|
|
1021
1062
|
} catch (err) {
|
|
1022
|
-
console.warn(` Task #${createdTask.
|
|
1063
|
+
console.warn(` Task #${createdTask.key} criada, mas falhou ao vincular ao RFC: ${err.message}`);
|
|
1023
1064
|
}
|
|
1024
1065
|
try {
|
|
1025
|
-
await moveToReady(
|
|
1066
|
+
await moveToReady(board, createdTask.key, createdTask.id, 'Task');
|
|
1026
1067
|
} catch (err) {
|
|
1027
|
-
console.warn(` Falha ao mover task #${createdTask.
|
|
1028
|
-
boardFailures.push({ number: createdTask.
|
|
1068
|
+
console.warn(` Falha ao mover task #${createdTask.key} para "${STAGE_READY}": ${err.message}`);
|
|
1069
|
+
boardFailures.push({ number: createdTask.key, kind: 'Task', reason: err.message });
|
|
1029
1070
|
}
|
|
1030
1071
|
}
|
|
1031
1072
|
|
|
1032
1073
|
const list = created.map(t => `- ${t.url} — ${t.title}`).join('\n');
|
|
1033
1074
|
const posicionamento = boardFailures.length === 0
|
|
1034
|
-
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx
|
|
1075
|
+
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx ${cliRef()} implement <task>\`.`
|
|
1035
1076
|
: renderBoardFailures(boardFailures);
|
|
1036
|
-
await
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1077
|
+
await tracker.addComment({
|
|
1078
|
+
ref: { key: String(parseInt(issueNumber, 10)) },
|
|
1079
|
+
body:
|
|
1080
|
+
`🔀 **Decomposição do RFC aplicada!**\n\n` +
|
|
1081
|
+
`A partir de \`${docRel}\` foram criadas ${created.length} tasks:\n\n${list}\n\n` +
|
|
1082
|
+
milestoneLine(issue, milestone) +
|
|
1083
|
+
posicionamento +
|
|
1084
|
+
formatItemsLintWarning(generatedTexts),
|
|
1085
|
+
}).catch(err => console.warn(`Falha ao comentar a decomposição: ${err.message}`));
|
|
1043
1086
|
console.log(`Decomposição aplicada: ${created.length} tasks criadas.`);
|
|
1044
1087
|
return boardFailures;
|
|
1045
1088
|
}
|
|
1046
1089
|
|
|
1047
1090
|
// Projeto + campos Etapa/Status do board (reutilizados em todos os itens).
|
|
1048
|
-
async function resolveBoard({ projectToken, root }, { strict = false } = {}) {
|
|
1049
|
-
const {
|
|
1091
|
+
async function resolveBoard({ token, projectToken, owner, repo, root }, { strict = false } = {}) {
|
|
1092
|
+
const { tracker, error: projectError } = openTracker({
|
|
1093
|
+
token, projectToken, owner, repo, cwd: root || process.cwd(),
|
|
1094
|
+
});
|
|
1050
1095
|
if (projectError) {
|
|
1051
1096
|
if (strict) throw new BoardUnreachableError(projectError);
|
|
1052
1097
|
console.warn(`${projectError} — itens criados não serão posicionados no board.`);
|
|
1098
|
+
return { tracker: null };
|
|
1053
1099
|
}
|
|
1054
1100
|
|
|
1055
|
-
// PREFLIGHT do apply:
|
|
1101
|
+
// PREFLIGHT do apply: alcançar o board ANTES de criar qualquer issue.
|
|
1102
|
+
//
|
|
1103
|
+
// A resolução de campo NÃO serve como preflight: ela devolve do cache do
|
|
1104
|
+
// config (`project.fields`) sem tocar a rede, então um token sem acesso ao
|
|
1105
|
+
// Project passava aqui limpo e só falhava na primeira mutação — depois de 27
|
|
1106
|
+
// issues criadas. Elas nascem sem Etapa, e sem Etapa somem de TODAS as telas
|
|
1107
|
+
// (o inbox do PM lista Features, a tela do Dev lê 🚧 Desenvolvimento, a fila
|
|
1108
|
+
// do TL lê ✅ Ready). Vinte e sete issues existindo e nenhuma aparecendo, com
|
|
1109
|
+
// o Action verde.
|
|
1056
1110
|
//
|
|
1057
|
-
// `
|
|
1058
|
-
//
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
// do PM lista Features, a tela do Dev lê 🚧 Desenvolvimento, a fila do TL lê
|
|
1062
|
-
// ✅ Ready). Vinte e sete issues existindo e nenhuma aparecendo, com o Action
|
|
1063
|
-
// verde. `getProjectSnapshot` faz `node(id:)` e é exatamente o que falha
|
|
1064
|
-
// quando o token não alcança o Project da organização.
|
|
1065
|
-
if (strict && project?.id) {
|
|
1111
|
+
// `tracker.verify()` é a operação que faz essa pergunta de forma portável:
|
|
1112
|
+
// ela TOCA a rede e devolve os problemas em vez de um booleano.
|
|
1113
|
+
if (strict) {
|
|
1114
|
+
let diag;
|
|
1066
1115
|
try {
|
|
1067
|
-
await
|
|
1116
|
+
diag = await tracker.verify();
|
|
1068
1117
|
} catch (err) {
|
|
1118
|
+
throw new BoardUnreachableError(`o board não pôde ser verificado (${err.message})`);
|
|
1119
|
+
}
|
|
1120
|
+
if (!diag.ok) {
|
|
1069
1121
|
throw new BoardUnreachableError(
|
|
1070
|
-
`o
|
|
1122
|
+
`o board não pôde ser alcançado com o token disponível (${diag.problems.join('; ')})`
|
|
1071
1123
|
);
|
|
1072
1124
|
}
|
|
1073
1125
|
}
|
|
1074
|
-
|
|
1075
|
-
let etapaField = null;
|
|
1076
|
-
let statusField = null;
|
|
1077
|
-
let typeField = null;
|
|
1078
|
-
if (project?.id) {
|
|
1079
|
-
try {
|
|
1080
|
-
etapaField = await resolveField(projectToken, project, 'Etapa');
|
|
1081
|
-
} catch (err) {
|
|
1082
|
-
if (strict) throw new BoardUnreachableError(`campo Etapa não resolvido (${err.message})`);
|
|
1083
|
-
console.warn(`Não foi possível resolver campo Etapa do board: ${err.message}`);
|
|
1084
|
-
}
|
|
1085
|
-
try {
|
|
1086
|
-
statusField = await resolveField(projectToken, project, 'Status');
|
|
1087
|
-
} catch (err) {
|
|
1088
|
-
if (strict) throw new BoardUnreachableError(`campo Status não resolvido (${err.message})`);
|
|
1089
|
-
console.warn(`Não foi possível resolver campo Status do board: ${err.message}`);
|
|
1090
|
-
}
|
|
1091
|
-
// NUNCA strict: o tipo é organização, não visibilidade. Um board sem o campo
|
|
1092
|
-
// "Work Item Type" continua sendo um board válido — sem Etapa, não.
|
|
1093
|
-
try {
|
|
1094
|
-
typeField = await resolveField(projectToken, project, 'Work Item Type');
|
|
1095
|
-
} catch (err) {
|
|
1096
|
-
console.warn(`Não foi possível resolver campo Work Item Type do board: ${err.message}`);
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
return { project, etapaField, statusField, typeField };
|
|
1126
|
+
return { tracker };
|
|
1100
1127
|
}
|
|
1101
1128
|
|
|
1102
1129
|
// ---------------------------------------------------------------------------
|
|
@@ -1153,7 +1180,8 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1153
1180
|
console.log(`Modo de execução: ${runMode}`);
|
|
1154
1181
|
|
|
1155
1182
|
const number = parseInt(issueNumber, 10);
|
|
1156
|
-
const
|
|
1183
|
+
const tracker = createGithubTracker({ token, projectToken, owner, repo });
|
|
1184
|
+
const issue = await tracker.getWorkItem({ ref: { key: String(number) } });
|
|
1157
1185
|
const type = detectIssueType(issue);
|
|
1158
1186
|
const labels = labelNames(issue);
|
|
1159
1187
|
const mode = resolveDecomposeMode({ labels, apply });
|
|
@@ -1162,23 +1190,27 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1162
1190
|
// Só Feature (→ Stories) e RFC (→ Tasks) podem ser decompostos.
|
|
1163
1191
|
if (!DECOMPOSE_TARGETS[type]) {
|
|
1164
1192
|
console.log(`Issue #${issueNumber} é ${type || 'desconhecido'} — decompose não se aplica.`);
|
|
1165
|
-
await
|
|
1166
|
-
await
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1193
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: trigger });
|
|
1194
|
+
await tracker.addComment({
|
|
1195
|
+
ref: { key: String(number) },
|
|
1196
|
+
body:
|
|
1197
|
+
`ℹ️ **decompose não se aplica a ${type || 'este tipo'}.** ` +
|
|
1198
|
+
`Use em **Features** (gera Stories + Tasks) ou **RFCs** (gera Tasks).`,
|
|
1199
|
+
}).catch(() => {});
|
|
1170
1200
|
return;
|
|
1171
1201
|
}
|
|
1172
1202
|
|
|
1173
1203
|
// Revisão humana pendente: nada roda até a label sair.
|
|
1174
1204
|
if (labels.includes(LABEL_NEEDS_HUMAN)) {
|
|
1175
1205
|
console.log(`Decompose ignorado: a issue tem a label ${LABEL_NEEDS_HUMAN}.`);
|
|
1176
|
-
await
|
|
1177
|
-
await
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1206
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: trigger });
|
|
1207
|
+
await tracker.addComment({
|
|
1208
|
+
ref: { key: String(number) },
|
|
1209
|
+
body:
|
|
1210
|
+
`⏸️ **decompose parado:** a issue tem a label \`${LABEL_NEEDS_HUMAN}\`, aplicada depois de ` +
|
|
1211
|
+
'reprovas consecutivas da crítica. Corrija os documentos e remova a label ' +
|
|
1212
|
+
`(e a \`${LABEL_CRITIQUE_FAILED}\`) para retomar o fluxo.`,
|
|
1213
|
+
}).catch(() => {});
|
|
1182
1214
|
return;
|
|
1183
1215
|
}
|
|
1184
1216
|
|
|
@@ -1186,7 +1218,7 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1186
1218
|
// tipo-alvo já existentes → não re-decompõe (evita duplicar stories/tasks).
|
|
1187
1219
|
let subIssues = [];
|
|
1188
1220
|
try {
|
|
1189
|
-
subIssues = await
|
|
1221
|
+
subIssues = await tracker.listChildren({ ref: issue.ref });
|
|
1190
1222
|
} catch (err) {
|
|
1191
1223
|
console.warn(`Não foi possível listar sub-issues: ${err.message} — seguindo sem o guard de sub-issues.`);
|
|
1192
1224
|
subIssues = [];
|
|
@@ -1194,11 +1226,13 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1194
1226
|
const guard = shouldSkipDecompose({ labels, subIssues, type });
|
|
1195
1227
|
if (guard.skip) {
|
|
1196
1228
|
console.log(`Decompose ignorado: ${guard.reason}.`);
|
|
1197
|
-
await
|
|
1198
|
-
await
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1229
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: trigger });
|
|
1230
|
+
await tracker.addComment({
|
|
1231
|
+
ref: { key: String(number) },
|
|
1232
|
+
body:
|
|
1233
|
+
`⏭️ **decompose ignorado:** ${guard.reason}. Para forçar, remova a label ` +
|
|
1234
|
+
`\`${LABEL_DECOMPOSED}\` (e apague as sub-issues antigas se quiser re-gerar).`,
|
|
1235
|
+
}).catch(() => {});
|
|
1202
1236
|
return;
|
|
1203
1237
|
}
|
|
1204
1238
|
|
|
@@ -1210,12 +1244,13 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1210
1244
|
// Branch base: é dela que os documentos são lidos quando não estão no clone, e
|
|
1211
1245
|
// é contra ela que o PR do rascunho é aberto. Best-effort — sem ela a leitura
|
|
1212
1246
|
// cai para o default da API, que é o mesmo lugar.
|
|
1213
|
-
const base = await
|
|
1247
|
+
const base = await createGithubScm({ link: githubLink({ owner, repo }), token })
|
|
1248
|
+
.defaultBranch().catch(() => null);
|
|
1214
1249
|
|
|
1215
1250
|
// Comentários só são necessários no rascunho (contador de tentativas).
|
|
1216
1251
|
let comments = [];
|
|
1217
1252
|
if (mode === 'draft') {
|
|
1218
|
-
comments = await
|
|
1253
|
+
comments = await tracker.listComments({ ref: { key: String(number) } })
|
|
1219
1254
|
.catch(err => {
|
|
1220
1255
|
console.warn(`Não foi possível listar comentários: ${err.message} — contador de tentativas em 1.`);
|
|
1221
1256
|
return [];
|
|
@@ -1226,7 +1261,7 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1226
1261
|
// fluxos que abortam (ex.: crítica grave) ou que falham.
|
|
1227
1262
|
const usageEntries = [];
|
|
1228
1263
|
const ctx = {
|
|
1229
|
-
token, projectToken, owner, repo, issue, issueNumber, type, labels, comments,
|
|
1264
|
+
token, projectToken, owner, repo, tracker, issue, issueNumber, type, labels, comments,
|
|
1230
1265
|
root, runMode, docRel: `${docRel}/${DECOMPOSITION_FILE}`,
|
|
1231
1266
|
dirRel: docRel,
|
|
1232
1267
|
base,
|
|
@@ -1254,12 +1289,14 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1254
1289
|
} catch (err) {
|
|
1255
1290
|
// Paradas por decisão do fluxo já comentaram na issue; erros inesperados não.
|
|
1256
1291
|
if (!err.blocked) {
|
|
1257
|
-
await
|
|
1258
|
-
await
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1292
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: trigger }).catch(() => {});
|
|
1293
|
+
await tracker.addComment({
|
|
1294
|
+
ref: { key: String(number) },
|
|
1295
|
+
body:
|
|
1296
|
+
renderApplyFailureComment({
|
|
1297
|
+
trigger, message: err.message, createdItems: ctx.createdItems, mode,
|
|
1298
|
+
}),
|
|
1299
|
+
}).catch(() => {});
|
|
1263
1300
|
}
|
|
1264
1301
|
throw err;
|
|
1265
1302
|
} finally {
|