@spec-wave/cli 1.0.8 → 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 +89 -58
- package/src/commands/decompose.mjs +254 -218
- package/src/commands/generate-bug.mjs +51 -44
- package/src/commands/generate-plan.mjs +83 -63
- package/src/commands/generate-qa-plan.mjs +144 -117
- package/src/commands/generate-spec.mjs +33 -28
- package/src/commands/implement.mjs +154 -79
- package/src/commands/init.mjs +8 -3
- package/src/commands/issue.mjs +26 -39
- package/src/commands/merge.mjs +71 -20
- package/src/commands/mode.mjs +8 -4
- 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 +28 -16
- package/src/commands/qa-run.mjs +122 -101
- 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 +10 -3
- 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 +29 -21
- 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/doc-availability.mjs +10 -3
- package/src/lib/doc-source.mjs +9 -9
- package/src/lib/implement-board.mjs +23 -26
- package/src/lib/issue-type.mjs +5 -1
- 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/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
|
@@ -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,
|
|
@@ -61,12 +59,15 @@ import {
|
|
|
61
59
|
// `itemType` é o tipo do que ACABOU de ser criado ('Story'/'Task'/'Feature') —
|
|
62
60
|
// aqui não há dúvida sobre ele, e sem essa passagem o Work Item Type das issues
|
|
63
61
|
// nascidas do apply ficava vazio para sempre (ver ensureWorkItemType).
|
|
64
|
-
async function moveToReady(
|
|
65
|
-
if (!
|
|
66
|
-
await advanceToStage(
|
|
67
|
-
|
|
68
|
-
{
|
|
69
|
-
|
|
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
|
+
});
|
|
70
71
|
}
|
|
71
72
|
|
|
72
73
|
/**
|
|
@@ -214,7 +215,10 @@ export function shouldSkipDecompose({ labels = [], subIssues = [], type } = {})
|
|
|
214
215
|
if (prefix) {
|
|
215
216
|
const existing = subIssues.find(s => (s.title || '').includes(prefix));
|
|
216
217
|
if (existing) {
|
|
217
|
-
|
|
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})` : '';
|
|
218
222
|
return { skip: true, reason: `a issue já tem sub-issues \`${prefix}\`${ref}` };
|
|
219
223
|
}
|
|
220
224
|
}
|
|
@@ -268,7 +272,10 @@ async function publishFile(ctx, { doc, pathRel, content, nextLabel = null, extra
|
|
|
268
272
|
token, owner, repo, doc,
|
|
269
273
|
issueNumber: parseInt(issueNumber, 10),
|
|
270
274
|
issueTitle: issue?.title || '',
|
|
271
|
-
|
|
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 || '',
|
|
272
279
|
pathRel, content, base, nextLabel, extraFiles,
|
|
273
280
|
});
|
|
274
281
|
if (published.warning) console.warn(`⚠️ ${published.warning}`);
|
|
@@ -303,7 +310,7 @@ export function codeReposPromptSection(config) {
|
|
|
303
310
|
|
|
304
311
|
async function draftDecomposition(ctx) {
|
|
305
312
|
const {
|
|
306
|
-
token, owner, repo, issue, issueNumber, type, labels, usage, root, runMode,
|
|
313
|
+
token, owner, repo, tracker, issue, issueNumber, type, labels, usage, root, runMode,
|
|
307
314
|
docRel, dirRel, base,
|
|
308
315
|
} = ctx;
|
|
309
316
|
const number = parseInt(issueNumber, 10);
|
|
@@ -323,11 +330,13 @@ async function draftDecomposition(ctx) {
|
|
|
323
330
|
const bloqueio = awaitingMergeBlock({
|
|
324
331
|
pathRel: `${dirRel}/${nome}`, state: doc.state, pr: doc.pr, branch: doc.ref,
|
|
325
332
|
});
|
|
326
|
-
await
|
|
327
|
-
await
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
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(() => {});
|
|
331
340
|
throw new DecomposeBlockedError(bloqueio.message);
|
|
332
341
|
}
|
|
333
342
|
}
|
|
@@ -418,13 +427,15 @@ async function draftDecomposition(ctx) {
|
|
|
418
427
|
try {
|
|
419
428
|
doc = parseDecompositionDoc(markdown);
|
|
420
429
|
} catch (err) {
|
|
421
|
-
await
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
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(() => {});
|
|
428
439
|
throw new DecomposeBlockedError(err.message);
|
|
429
440
|
}
|
|
430
441
|
const itemCount = kind === 'stories'
|
|
@@ -445,14 +456,18 @@ async function draftDecomposition(ctx) {
|
|
|
445
456
|
const decisions = parseCritiqueDecisions(ctx.comments, 'stories');
|
|
446
457
|
if (blocked) {
|
|
447
458
|
console.log(`Teto de ${ctx.maxCritiqueAttempts} tentativas de crítica atingido — exigindo revisão humana.`);
|
|
448
|
-
await
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
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 });
|
|
456
471
|
throw new DecomposeBlockedError(
|
|
457
472
|
`A crítica reprovou ${ctx.maxCritiqueAttempts - 1}x seguidas. Label ${LABEL_NEEDS_HUMAN} ` +
|
|
458
473
|
'aplicada: o fluxo exige revisão humana antes de continuar.'
|
|
@@ -481,18 +496,20 @@ async function draftDecomposition(ctx) {
|
|
|
481
496
|
// A crítica é o portão que impede stories contraditórias de virarem trabalho.
|
|
482
497
|
// Liberar o rascunho com o portão comprovadamente não executado é exatamente
|
|
483
498
|
// o que se quer evitar — então aborta, e a Action fica vermelha.
|
|
484
|
-
await
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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(() => {});
|
|
492
509
|
throw new DecomposeBlockedError(`Crítica adversarial não concluiu: ${err.message}`);
|
|
493
510
|
}
|
|
494
511
|
|
|
495
|
-
await
|
|
512
|
+
await tracker.addComment({ ref: { key: String(number) }, body: critique.markdown })
|
|
496
513
|
.catch(err => console.warn(`Falha ao comentar a crítica: ${err.message}`));
|
|
497
514
|
|
|
498
515
|
// Graves SEM decisão do TL. É este o portão que travava a #18: com spec e
|
|
@@ -500,15 +517,14 @@ async function draftDecomposition(ctx) {
|
|
|
500
517
|
// um documento está certo, ou aceitar o risco, item a item.
|
|
501
518
|
const { blocking, accepted } = applyCritiqueDecisions(critique.findings, decisions, 'stories');
|
|
502
519
|
if (accepted.length > 0) {
|
|
503
|
-
await
|
|
504
|
-
await
|
|
505
|
-
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(() => {});
|
|
506
522
|
}
|
|
507
523
|
if (blocking.length > 0) {
|
|
508
524
|
console.log(`Crítica adversarial apontou ${blocking.length} finding(s) GRAVE(s) sem decisão — nenhum item foi criado.`);
|
|
509
|
-
await
|
|
510
|
-
await
|
|
511
|
-
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 });
|
|
512
528
|
throw new DecomposeBlockedError(
|
|
513
529
|
`A crítica adversarial apontou findings graves no rascunho (tentativa ${attempt}). ` +
|
|
514
530
|
`Nenhuma issue foi criada. Corrija ${docRel} e reaplique ${LABEL_DECOMPOSE}.`
|
|
@@ -517,17 +533,17 @@ async function draftDecomposition(ctx) {
|
|
|
517
533
|
|
|
518
534
|
// Crítica limpa: remove o bloqueio anterior, que também zera o contador de
|
|
519
535
|
// tentativas na próxima rodada (ver resolveCritiqueAttempt).
|
|
520
|
-
await
|
|
536
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_CRITIQUE_FAILED }).catch(() => {});
|
|
521
537
|
return await finishDraft(ctx, { doc, blobUrl, itemCount, critiqued: true, publicado });
|
|
522
538
|
}
|
|
523
539
|
|
|
524
540
|
// Fecho comum do rascunho aprovado: libera para revisão humana e o apply.
|
|
525
541
|
async function finishDraft(
|
|
526
|
-
{
|
|
542
|
+
{ tracker, issueNumber, docRel }, { blobUrl, itemCount, critiqued, publicado }
|
|
527
543
|
) {
|
|
528
544
|
const number = parseInt(issueNumber, 10);
|
|
529
|
-
await
|
|
530
|
-
await
|
|
545
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_READY });
|
|
546
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE });
|
|
531
547
|
|
|
532
548
|
// O apply LÊ o rascunho da branch base, então ele só roda depois do merge —
|
|
533
549
|
// dizer "crie as issues agora" sem essa ressalva manda o humano num passo que
|
|
@@ -539,18 +555,20 @@ async function finishDraft(
|
|
|
539
555
|
'faça o merge e então crie as issues:\n'
|
|
540
556
|
: '**Nada foi criado ainda.** Revise (e edite, se quiser) o arquivo e então crie as issues:\n';
|
|
541
557
|
|
|
542
|
-
await
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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}`));
|
|
554
572
|
console.log(`Rascunho liberado para revisão: ${itemCount}.`);
|
|
555
573
|
return { pr: pr || null };
|
|
556
574
|
}
|
|
@@ -560,7 +578,7 @@ async function finishDraft(
|
|
|
560
578
|
// ---------------------------------------------------------------------------
|
|
561
579
|
|
|
562
580
|
async function applyDecomposition(ctx) {
|
|
563
|
-
const { token, owner, repo, issueNumber, docRel, root, base } = ctx;
|
|
581
|
+
const { token, owner, repo, tracker, issueNumber, docRel, root, base } = ctx;
|
|
564
582
|
const number = parseInt(issueNumber, 10);
|
|
565
583
|
|
|
566
584
|
const rascunho = await loadArtifact({
|
|
@@ -579,21 +597,25 @@ async function applyDecomposition(ctx) {
|
|
|
579
597
|
const bloqueio = awaitingMergeBlock({
|
|
580
598
|
pathRel: docRel, state: rascunho.state, pr: rascunho.pr, branch: rascunho.ref,
|
|
581
599
|
});
|
|
582
|
-
await
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
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(() => {});
|
|
587
607
|
throw new DecomposeBlockedError(bloqueio.message);
|
|
588
608
|
}
|
|
589
609
|
|
|
590
610
|
if (rascunho.content == null) {
|
|
591
|
-
await
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
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(() => {});
|
|
597
619
|
throw new DecomposeBlockedError(`${docRel} não encontrado — aplique ${LABEL_DECOMPOSE} primeiro.`);
|
|
598
620
|
}
|
|
599
621
|
|
|
@@ -601,12 +623,14 @@ async function applyDecomposition(ctx) {
|
|
|
601
623
|
try {
|
|
602
624
|
doc = parseDecompositionDoc(rascunho.content);
|
|
603
625
|
} catch (err) {
|
|
604
|
-
await
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
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(() => {});
|
|
610
634
|
throw new DecomposeBlockedError(err.message);
|
|
611
635
|
}
|
|
612
636
|
|
|
@@ -622,8 +646,8 @@ async function applyDecomposition(ctx) {
|
|
|
622
646
|
|
|
623
647
|
// Campos do board só são resolvidos aqui: a etapa de rascunho não toca o board.
|
|
624
648
|
// `strict`: no apply, board inalcançável ABORTA antes da primeira criação.
|
|
625
|
-
const
|
|
626
|
-
const applyCtx = { ...ctx,
|
|
649
|
+
const board = await resolveBoard(ctx, { strict: true });
|
|
650
|
+
const applyCtx = { ...ctx, board };
|
|
627
651
|
|
|
628
652
|
// As falhas de board voltam em vez de subir na hora: a exceção precisa esperar
|
|
629
653
|
// a contabilidade de labels abaixo. Lançar aqui deixaria o gatilho
|
|
@@ -687,19 +711,19 @@ async function applyDecomposition(ctx) {
|
|
|
687
711
|
// mentiria por até um TTL inteiro.
|
|
688
712
|
invalidateCache(ctx.root, `subissues-${number}`, 'board-items');
|
|
689
713
|
|
|
690
|
-
await
|
|
714
|
+
await tracker.addTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSED })
|
|
691
715
|
.catch(err => console.warn(`Falha ao aplicar a label ${LABEL_DECOMPOSED}: ${err.message}`));
|
|
692
716
|
// Best-effort como as duas vizinhas: as issues já existem, e derrubar o run
|
|
693
717
|
// porque a REMOÇÃO de uma label falhou (404 de label já removida por um run
|
|
694
718
|
// concorrente, 5xx da API) transformava um apply concluído em vermelho — e o
|
|
695
719
|
// vermelho manda o humano reaplicar o gatilho, que é o caminho para duplicar
|
|
696
720
|
// dezenas de issues. A label que sobra é visível na issue e removível à mão.
|
|
697
|
-
await
|
|
721
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_APPLY })
|
|
698
722
|
.catch(err => console.warn(
|
|
699
723
|
`Decomposição aplicada, mas a label ${LABEL_DECOMPOSE_APPLY} não pôde ser removida ` +
|
|
700
724
|
`(${err.message}). Remova-a à mão: gh issue edit ${number} --remove-label "${LABEL_DECOMPOSE_APPLY}".`
|
|
701
725
|
));
|
|
702
|
-
await
|
|
726
|
+
await tracker.removeTag({ ref: { key: String(number) }, tag: LABEL_DECOMPOSE_READY }).catch(() => {});
|
|
703
727
|
|
|
704
728
|
// Por último, com as labels já consistentes: escrita de board incompleta
|
|
705
729
|
// termina o run em VERMELHO.
|
|
@@ -766,7 +790,7 @@ function milestoneLine(issue, milestone) {
|
|
|
766
790
|
*
|
|
767
791
|
* @returns {Promise<Map<number, {number:number, id:number, title:string}>>}
|
|
768
792
|
*/
|
|
769
|
-
async function resolveExternalDeps({
|
|
793
|
+
async function resolveExternalDeps({ tracker }, doc) {
|
|
770
794
|
const numeros = [...new Set(
|
|
771
795
|
(doc.stories || []).flatMap(s => s.dependsOnIssues || [])
|
|
772
796
|
)].sort((a, b) => a - b);
|
|
@@ -774,8 +798,10 @@ async function resolveExternalDeps({ token, owner, repo }, doc) {
|
|
|
774
798
|
const faltando = [];
|
|
775
799
|
for (const n of numeros) {
|
|
776
800
|
try {
|
|
777
|
-
const
|
|
778
|
-
|
|
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 });
|
|
779
805
|
} catch (err) {
|
|
780
806
|
faltando.push(`#${n} (${err.status === 404 ? 'não existe' : err.message})`);
|
|
781
807
|
}
|
|
@@ -802,7 +828,7 @@ async function resolveExternalDeps({ token, owner, repo }, doc) {
|
|
|
802
828
|
*
|
|
803
829
|
* @returns {Promise<Map<string, string[]>>} anchor da Story → labels
|
|
804
830
|
*/
|
|
805
|
-
async function resolveRepoLabels({
|
|
831
|
+
async function resolveRepoLabels({ tracker, config }, doc) {
|
|
806
832
|
const porStory = new Map();
|
|
807
833
|
const slugs = [...new Set((doc.stories || []).flatMap(s => s.repos || []))].sort();
|
|
808
834
|
if (slugs.length === 0) return porStory;
|
|
@@ -822,7 +848,7 @@ async function resolveRepoLabels({ token, owner, repo, config }, doc) {
|
|
|
822
848
|
const spec = repoLabelSpec(slug);
|
|
823
849
|
try {
|
|
824
850
|
// createLabel já engole o 422 de "já existe".
|
|
825
|
-
await
|
|
851
|
+
await tracker.ensureTags({ tags: [spec] });
|
|
826
852
|
} catch (err) {
|
|
827
853
|
console.warn(` Não consegui garantir a label ${spec.name}: ${err.message}`);
|
|
828
854
|
}
|
|
@@ -834,9 +860,8 @@ async function resolveRepoLabels({ token, owner, repo, config }, doc) {
|
|
|
834
860
|
}
|
|
835
861
|
|
|
836
862
|
async function createStoriesFromDoc(ctx, doc) {
|
|
837
|
-
const { token,
|
|
838
|
-
const
|
|
839
|
-
const featureNodeId = issue.node_id;
|
|
863
|
+
const { token, owner, repo, tracker, issue, issueNumber, board, docRel } = ctx;
|
|
864
|
+
const featureNodeId = issue.ref.id;
|
|
840
865
|
// Herdado uma vez e reusado por todas as Stories e Tasks deste apply.
|
|
841
866
|
const milestone = resolveInheritedMilestone(issue);
|
|
842
867
|
if (milestone) console.log(`Milestone herdado da ${ctx.type}: ${issue.milestone?.title ?? `#${milestone}`}.`);
|
|
@@ -867,17 +892,25 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
867
892
|
...story.dependsOn.map(idx => createdStories[idx]),
|
|
868
893
|
...(story.dependsOnIssues || []).map(n => externas.get(n)),
|
|
869
894
|
].filter(Boolean);
|
|
870
|
-
|
|
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));
|
|
871
900
|
if (depLine) storyBody += `\n\n${depLine}`;
|
|
872
901
|
|
|
873
902
|
// `repo:<slug>` já na criação (RFC-005 §6.2 item 6) — a label é a fonte de
|
|
874
903
|
// verdade de quais repositórios a Story toca; o campo do board é só espelho.
|
|
875
904
|
const labelsDoRepo = repoLabels.get(story.anchor) || [];
|
|
876
|
-
const createdStory = await
|
|
877
|
-
|
|
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);
|
|
878
911
|
// Anota no doc em memória: é daqui que sai o `**Issue:** #N` gravado no
|
|
879
912
|
// arquivo no fim do apply.
|
|
880
|
-
story.issue = createdStory.
|
|
913
|
+
story.issue = createdStory.key;
|
|
881
914
|
created.push({ title: storyTitle, url: createdStory.url });
|
|
882
915
|
createdStories.push(createdStory);
|
|
883
916
|
generatedTexts.push(storyTitle, storyBody);
|
|
@@ -885,22 +918,22 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
885
918
|
// Relação nativa blocked_by (best-effort — a linha "Depende de" já basta).
|
|
886
919
|
for (const dep of depIssues) {
|
|
887
920
|
try {
|
|
888
|
-
await addBlockedBy(
|
|
921
|
+
await tracker.addBlockedBy({ ref: createdStory, blockedBy: dep.ref ?? dep });
|
|
889
922
|
} catch (err) {
|
|
890
|
-
console.warn(` Falha ao marcar story #${createdStory.
|
|
923
|
+
console.warn(` Falha ao marcar story #${createdStory.key} como bloqueada por #${depNumero(dep)}: ${err.message}`);
|
|
891
924
|
}
|
|
892
925
|
}
|
|
893
926
|
|
|
894
927
|
try {
|
|
895
|
-
await
|
|
928
|
+
await tracker.addChild({ parent: { key: String(issueNumber), id: featureNodeId }, child: createdStory });
|
|
896
929
|
} catch (err) {
|
|
897
|
-
console.warn(` Story #${createdStory.
|
|
930
|
+
console.warn(` Story #${createdStory.key} criada, mas falhou ao vincular à Feature: ${err.message}`);
|
|
898
931
|
}
|
|
899
932
|
try {
|
|
900
|
-
await moveToReady(
|
|
933
|
+
await moveToReady(board, createdStory.key, createdStory.id, 'Story');
|
|
901
934
|
} catch (err) {
|
|
902
|
-
console.warn(` Falha ao mover story #${createdStory.
|
|
903
|
-
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 });
|
|
904
937
|
}
|
|
905
938
|
|
|
906
939
|
for (const task of story.tasks || []) {
|
|
@@ -909,27 +942,31 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
909
942
|
const taskBody = `${task.body}\n\n_Story pai: ${createdStory.url}_`;
|
|
910
943
|
// A Task herda os repos da Story (RFC-005 §5.2, `effectiveRepoSlugs`) —
|
|
911
944
|
// gravado na label em vez de inferido, para `order`/`implement` lerem direto.
|
|
912
|
-
const createdTask = await
|
|
913
|
-
|
|
914
|
-
|
|
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;
|
|
915
952
|
generatedTexts.push(taskTitle, taskBody);
|
|
916
953
|
try {
|
|
917
|
-
await
|
|
954
|
+
await tracker.addChild({ parent: createdStory, child: createdTask });
|
|
918
955
|
} catch (err) {
|
|
919
|
-
console.warn(` Task #${createdTask.
|
|
956
|
+
console.warn(` Task #${createdTask.key} criada, mas falhou ao vincular à Story: ${err.message}`);
|
|
920
957
|
}
|
|
921
958
|
try {
|
|
922
|
-
await moveToReady(
|
|
959
|
+
await moveToReady(board, createdTask.key, createdTask.id, 'Task');
|
|
923
960
|
} catch (err) {
|
|
924
|
-
console.warn(` Falha ao mover task #${createdTask.
|
|
925
|
-
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 });
|
|
926
963
|
}
|
|
927
964
|
}
|
|
928
965
|
}
|
|
929
966
|
|
|
930
967
|
try {
|
|
931
|
-
await moveToReady(
|
|
932
|
-
if (
|
|
968
|
+
await moveToReady(board, issueNumber, featureNodeId, ctx.type);
|
|
969
|
+
if (board?.tracker) console.log(`Feature movida para "${STAGE_READY}" no board.`);
|
|
933
970
|
} catch (err) {
|
|
934
971
|
console.warn(`Falha ao mover Feature para "${STAGE_READY}": ${err.message}`);
|
|
935
972
|
boardFailures.push({ number: parseInt(issueNumber, 10), kind: 'Feature', reason: err.message });
|
|
@@ -939,15 +976,17 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
939
976
|
const posicionamento = boardFailures.length === 0
|
|
940
977
|
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx ${cliRef()} implement ${issueNumber}\` (Stories em ordem de dependência).`
|
|
941
978
|
: renderBoardFailures(boardFailures);
|
|
942
|
-
await
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
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 });
|
|
951
990
|
|
|
952
991
|
console.log(`Decomposição aplicada: ${created.length} stories criadas.`);
|
|
953
992
|
return boardFailures;
|
|
@@ -965,18 +1004,18 @@ async function createStoriesFromDoc(ctx, doc) {
|
|
|
965
1004
|
* BEST-EFFORT, como o comentário que o antecede: a decomposição está feita e
|
|
966
1005
|
* paga, e falhar ao comentar não pode desfazê-la nem mascarar o que deu certo.
|
|
967
1006
|
*/
|
|
968
|
-
async function commentStoryOrder({
|
|
1007
|
+
async function commentStoryOrder({ tracker, issueNumber, doc, createdStories }) {
|
|
969
1008
|
try {
|
|
970
1009
|
const stories = doc.stories
|
|
971
1010
|
.map((story, i) => {
|
|
972
1011
|
const criada = createdStories[i];
|
|
973
1012
|
if (!criada) return null; // criação falhou no meio: não inventa a Story
|
|
974
1013
|
return {
|
|
975
|
-
number: criada.
|
|
1014
|
+
number: Number(criada.key),
|
|
976
1015
|
title: story.title,
|
|
977
1016
|
// dependsOn vem 0-based (índice no doc) e vira número de issue.
|
|
978
1017
|
dependsOn: (story.dependsOn || [])
|
|
979
|
-
.map(idx => createdStories[idx]
|
|
1018
|
+
.map(idx => createdStories[idx] && Number(createdStories[idx].key))
|
|
980
1019
|
.filter(Boolean),
|
|
981
1020
|
};
|
|
982
1021
|
})
|
|
@@ -989,8 +1028,7 @@ async function commentStoryOrder({ token, owner, repo, issueNumber, doc, created
|
|
|
989
1028
|
stories.map(({ number, dependsOn }) => ({ number, dependsOn }))
|
|
990
1029
|
);
|
|
991
1030
|
|
|
992
|
-
await
|
|
993
|
-
renderOrderComment({ sorted, cycle, byNumber }));
|
|
1031
|
+
await tracker.addComment({ ref: { key: String(parseInt(issueNumber, 10)) }, body: renderOrderComment({ sorted, cycle, byNumber }) });
|
|
994
1032
|
console.log(`Ordem de execução comentada: ${sorted.length} story(ies).`);
|
|
995
1033
|
} catch (err) {
|
|
996
1034
|
console.warn(`Falha ao comentar a ordem de execução: ${err.message}`);
|
|
@@ -998,9 +1036,8 @@ async function commentStoryOrder({ token, owner, repo, issueNumber, doc, created
|
|
|
998
1036
|
}
|
|
999
1037
|
|
|
1000
1038
|
async function createTasksFromDoc(ctx, doc) {
|
|
1001
|
-
const { token,
|
|
1002
|
-
const
|
|
1003
|
-
const parentNodeId = issue.node_id;
|
|
1039
|
+
const { token, owner, repo, tracker, issue, issueNumber, board, docRel } = ctx;
|
|
1040
|
+
const parentNodeId = issue.ref.id;
|
|
1004
1041
|
const milestone = resolveInheritedMilestone(issue);
|
|
1005
1042
|
if (milestone) console.log(`Milestone herdado do RFC: ${issue.milestone?.title ?? `#${milestone}`}.`);
|
|
1006
1043
|
const created = [];
|
|
@@ -1010,23 +1047,26 @@ async function createTasksFromDoc(ctx, doc) {
|
|
|
1010
1047
|
for (const task of doc.tasks) {
|
|
1011
1048
|
console.log(`Criando task: ${task.title}`);
|
|
1012
1049
|
const taskTitle = `[TASK] ${task.title}`;
|
|
1013
|
-
const taskBody = `${task.body}\n\n_RFC pai: ${issue.html_url || `#${issueNumber}`}_`;
|
|
1014
|
-
const createdTask = await
|
|
1015
|
-
|
|
1016
|
-
|
|
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;
|
|
1017
1057
|
created.push({ title: taskTitle, url: createdTask.url });
|
|
1018
1058
|
generatedTexts.push(taskTitle, taskBody);
|
|
1019
1059
|
|
|
1020
1060
|
try {
|
|
1021
|
-
await
|
|
1061
|
+
await tracker.addChild({ parent: { key: String(issueNumber), id: parentNodeId }, child: createdTask });
|
|
1022
1062
|
} catch (err) {
|
|
1023
|
-
console.warn(` Task #${createdTask.
|
|
1063
|
+
console.warn(` Task #${createdTask.key} criada, mas falhou ao vincular ao RFC: ${err.message}`);
|
|
1024
1064
|
}
|
|
1025
1065
|
try {
|
|
1026
|
-
await moveToReady(
|
|
1066
|
+
await moveToReady(board, createdTask.key, createdTask.id, 'Task');
|
|
1027
1067
|
} catch (err) {
|
|
1028
|
-
console.warn(` Falha ao mover task #${createdTask.
|
|
1029
|
-
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 });
|
|
1030
1070
|
}
|
|
1031
1071
|
}
|
|
1032
1072
|
|
|
@@ -1034,70 +1074,56 @@ async function createTasksFromDoc(ctx, doc) {
|
|
|
1034
1074
|
const posicionamento = boardFailures.length === 0
|
|
1035
1075
|
? `Tudo posicionado em **✅ Ready**. Inicie o desenvolvimento com \`npx ${cliRef()} implement <task>\`.`
|
|
1036
1076
|
: renderBoardFailures(boardFailures);
|
|
1037
|
-
await
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
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}`));
|
|
1044
1086
|
console.log(`Decomposição aplicada: ${created.length} tasks criadas.`);
|
|
1045
1087
|
return boardFailures;
|
|
1046
1088
|
}
|
|
1047
1089
|
|
|
1048
1090
|
// Projeto + campos Etapa/Status do board (reutilizados em todos os itens).
|
|
1049
|
-
async function resolveBoard({ projectToken, root }, { strict = false } = {}) {
|
|
1050
|
-
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
|
+
});
|
|
1051
1095
|
if (projectError) {
|
|
1052
1096
|
if (strict) throw new BoardUnreachableError(projectError);
|
|
1053
1097
|
console.warn(`${projectError} — itens criados não serão posicionados no board.`);
|
|
1098
|
+
return { tracker: null };
|
|
1054
1099
|
}
|
|
1055
1100
|
|
|
1056
|
-
// 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.
|
|
1057
1110
|
//
|
|
1058
|
-
// `
|
|
1059
|
-
//
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
// do PM lista Features, a tela do Dev lê 🚧 Desenvolvimento, a fila do TL lê
|
|
1063
|
-
// ✅ Ready). Vinte e sete issues existindo e nenhuma aparecendo, com o Action
|
|
1064
|
-
// verde. `getProjectSnapshot` faz `node(id:)` e é exatamente o que falha
|
|
1065
|
-
// quando o token não alcança o Project da organização.
|
|
1066
|
-
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;
|
|
1067
1115
|
try {
|
|
1068
|
-
await
|
|
1116
|
+
diag = await tracker.verify();
|
|
1069
1117
|
} catch (err) {
|
|
1118
|
+
throw new BoardUnreachableError(`o board não pôde ser verificado (${err.message})`);
|
|
1119
|
+
}
|
|
1120
|
+
if (!diag.ok) {
|
|
1070
1121
|
throw new BoardUnreachableError(
|
|
1071
|
-
`o
|
|
1122
|
+
`o board não pôde ser alcançado com o token disponível (${diag.problems.join('; ')})`
|
|
1072
1123
|
);
|
|
1073
1124
|
}
|
|
1074
1125
|
}
|
|
1075
|
-
|
|
1076
|
-
let etapaField = null;
|
|
1077
|
-
let statusField = null;
|
|
1078
|
-
let typeField = null;
|
|
1079
|
-
if (project?.id) {
|
|
1080
|
-
try {
|
|
1081
|
-
etapaField = await resolveField(projectToken, project, 'Etapa');
|
|
1082
|
-
} catch (err) {
|
|
1083
|
-
if (strict) throw new BoardUnreachableError(`campo Etapa não resolvido (${err.message})`);
|
|
1084
|
-
console.warn(`Não foi possível resolver campo Etapa do board: ${err.message}`);
|
|
1085
|
-
}
|
|
1086
|
-
try {
|
|
1087
|
-
statusField = await resolveField(projectToken, project, 'Status');
|
|
1088
|
-
} catch (err) {
|
|
1089
|
-
if (strict) throw new BoardUnreachableError(`campo Status não resolvido (${err.message})`);
|
|
1090
|
-
console.warn(`Não foi possível resolver campo Status do board: ${err.message}`);
|
|
1091
|
-
}
|
|
1092
|
-
// NUNCA strict: o tipo é organização, não visibilidade. Um board sem o campo
|
|
1093
|
-
// "Work Item Type" continua sendo um board válido — sem Etapa, não.
|
|
1094
|
-
try {
|
|
1095
|
-
typeField = await resolveField(projectToken, project, 'Work Item Type');
|
|
1096
|
-
} catch (err) {
|
|
1097
|
-
console.warn(`Não foi possível resolver campo Work Item Type do board: ${err.message}`);
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
return { project, etapaField, statusField, typeField };
|
|
1126
|
+
return { tracker };
|
|
1101
1127
|
}
|
|
1102
1128
|
|
|
1103
1129
|
// ---------------------------------------------------------------------------
|
|
@@ -1154,7 +1180,8 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1154
1180
|
console.log(`Modo de execução: ${runMode}`);
|
|
1155
1181
|
|
|
1156
1182
|
const number = parseInt(issueNumber, 10);
|
|
1157
|
-
const
|
|
1183
|
+
const tracker = createGithubTracker({ token, projectToken, owner, repo });
|
|
1184
|
+
const issue = await tracker.getWorkItem({ ref: { key: String(number) } });
|
|
1158
1185
|
const type = detectIssueType(issue);
|
|
1159
1186
|
const labels = labelNames(issue);
|
|
1160
1187
|
const mode = resolveDecomposeMode({ labels, apply });
|
|
@@ -1163,23 +1190,27 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1163
1190
|
// Só Feature (→ Stories) e RFC (→ Tasks) podem ser decompostos.
|
|
1164
1191
|
if (!DECOMPOSE_TARGETS[type]) {
|
|
1165
1192
|
console.log(`Issue #${issueNumber} é ${type || 'desconhecido'} — decompose não se aplica.`);
|
|
1166
|
-
await
|
|
1167
|
-
await
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
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(() => {});
|
|
1171
1200
|
return;
|
|
1172
1201
|
}
|
|
1173
1202
|
|
|
1174
1203
|
// Revisão humana pendente: nada roda até a label sair.
|
|
1175
1204
|
if (labels.includes(LABEL_NEEDS_HUMAN)) {
|
|
1176
1205
|
console.log(`Decompose ignorado: a issue tem a label ${LABEL_NEEDS_HUMAN}.`);
|
|
1177
|
-
await
|
|
1178
|
-
await
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
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(() => {});
|
|
1183
1214
|
return;
|
|
1184
1215
|
}
|
|
1185
1216
|
|
|
@@ -1187,7 +1218,7 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1187
1218
|
// tipo-alvo já existentes → não re-decompõe (evita duplicar stories/tasks).
|
|
1188
1219
|
let subIssues = [];
|
|
1189
1220
|
try {
|
|
1190
|
-
subIssues = await
|
|
1221
|
+
subIssues = await tracker.listChildren({ ref: issue.ref });
|
|
1191
1222
|
} catch (err) {
|
|
1192
1223
|
console.warn(`Não foi possível listar sub-issues: ${err.message} — seguindo sem o guard de sub-issues.`);
|
|
1193
1224
|
subIssues = [];
|
|
@@ -1195,11 +1226,13 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1195
1226
|
const guard = shouldSkipDecompose({ labels, subIssues, type });
|
|
1196
1227
|
if (guard.skip) {
|
|
1197
1228
|
console.log(`Decompose ignorado: ${guard.reason}.`);
|
|
1198
|
-
await
|
|
1199
|
-
await
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
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(() => {});
|
|
1203
1236
|
return;
|
|
1204
1237
|
}
|
|
1205
1238
|
|
|
@@ -1211,12 +1244,13 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1211
1244
|
// Branch base: é dela que os documentos são lidos quando não estão no clone, e
|
|
1212
1245
|
// é contra ela que o PR do rascunho é aberto. Best-effort — sem ela a leitura
|
|
1213
1246
|
// cai para o default da API, que é o mesmo lugar.
|
|
1214
|
-
const base = await
|
|
1247
|
+
const base = await createGithubScm({ link: githubLink({ owner, repo }), token })
|
|
1248
|
+
.defaultBranch().catch(() => null);
|
|
1215
1249
|
|
|
1216
1250
|
// Comentários só são necessários no rascunho (contador de tentativas).
|
|
1217
1251
|
let comments = [];
|
|
1218
1252
|
if (mode === 'draft') {
|
|
1219
|
-
comments = await
|
|
1253
|
+
comments = await tracker.listComments({ ref: { key: String(number) } })
|
|
1220
1254
|
.catch(err => {
|
|
1221
1255
|
console.warn(`Não foi possível listar comentários: ${err.message} — contador de tentativas em 1.`);
|
|
1222
1256
|
return [];
|
|
@@ -1227,7 +1261,7 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1227
1261
|
// fluxos que abortam (ex.: crítica grave) ou que falham.
|
|
1228
1262
|
const usageEntries = [];
|
|
1229
1263
|
const ctx = {
|
|
1230
|
-
token, projectToken, owner, repo, issue, issueNumber, type, labels, comments,
|
|
1264
|
+
token, projectToken, owner, repo, tracker, issue, issueNumber, type, labels, comments,
|
|
1231
1265
|
root, runMode, docRel: `${docRel}/${DECOMPOSITION_FILE}`,
|
|
1232
1266
|
dirRel: docRel,
|
|
1233
1267
|
base,
|
|
@@ -1255,12 +1289,14 @@ export async function decompose({ issueNumber, apply }) {
|
|
|
1255
1289
|
} catch (err) {
|
|
1256
1290
|
// Paradas por decisão do fluxo já comentaram na issue; erros inesperados não.
|
|
1257
1291
|
if (!err.blocked) {
|
|
1258
|
-
await
|
|
1259
|
-
await
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
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(() => {});
|
|
1264
1300
|
}
|
|
1265
1301
|
throw err;
|
|
1266
1302
|
} finally {
|