jarvis-ai-framework 8.3.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/AGENTS.md +46 -100
  2. package/README.md +2 -2
  3. package/agents/README.md +1 -0
  4. package/agents/engineering/data/eng.data-engineer.agent.md +8 -44
  5. package/agents/engineering/eng.agent.md +5 -80
  6. package/agents/engineering/eng.bug-hunter.md +1 -10
  7. package/agents/engineering/eng.dev-code-reviewer.md +1 -1
  8. package/agents/engineering/eng.docs-consolidator.agent.md +6 -3
  9. package/agents/engineering/eng.docs-writer.md +12 -87
  10. package/agents/engineering/eng.rpa.agent.md +6 -30
  11. package/agents/engineering/qa/eng.qa.test-architect.md +1 -33
  12. package/agents/engineering/qa/eng.qa.test-planner.md +3 -143
  13. package/agents/engineering/qa/eng.qa.testing-engineer.md +4 -53
  14. package/bin/README.md +8 -6
  15. package/bin/commands/docs-archive.js +86 -0
  16. package/bin/commands/docs-finalize.js +82 -0
  17. package/bin/commands/docs-migrate.js +107 -0
  18. package/bin/commands/docs-publish.js +132 -67
  19. package/bin/commands/docs-sync.js +12 -7
  20. package/bin/commands/init.js +92 -7
  21. package/bin/commands/rules.js +136 -0
  22. package/bin/lib/cli/program.js +65 -4
  23. package/bin/lib/config/constants.js +60 -39
  24. package/bin/lib/core/docs-migrate.js +2 -2
  25. package/bin/lib/core/env-upgrade.js +132 -16
  26. package/bin/lib/core/profile-filter.js +4 -9
  27. package/bin/lib/core/scanner.js +10 -4
  28. package/bin/lib/core/sync-engine.js +184 -51
  29. package/bin/lib/docs/finish-delivery.js +493 -0
  30. package/bin/lib/docs/migrate-central.js +229 -0
  31. package/bin/lib/docs/publish-file.js +176 -46
  32. package/bin/lib/docs/storage/build-index.js +83 -47
  33. package/bin/lib/docs/storage/filesystem.js +341 -6
  34. package/bin/lib/docs/storage/index.js +0 -1
  35. package/bin/lib/docs/validate-frontmatter.js +34 -2
  36. package/bin/lib/utils/frontmatter.js +36 -2
  37. package/package.json +2 -2
  38. package/rules/artifact-style-rules.md +1 -1
  39. package/rules/company-overlay-rules.md +0 -4
  40. package/rules/engineering/eng-rules.md +0 -4
  41. package/rules/engineering/eng-security-rules.md +1 -34
  42. package/rules/engineering/eng.integrations-rules.md +3 -3
  43. package/rules/engineering/eng.skills-rules.md +1 -1
  44. package/rules/engineering/eng.specializations-rules.md +1 -1
  45. package/rules/engineering/frontend/eng.frontend-rules.md +0 -3
  46. package/rules/engineering/qa/eng.qa.cypress-standards-rules.md +2 -256
  47. package/rules/product/prod-rules.md +9 -54
  48. package/rules/product/prod.spec-rules.md +1 -0
  49. package/rules/rtk-rules.md +0 -4
  50. package/rules-on-demand/engineering/eng.breakdown-subtasks-rules.md +3 -199
  51. package/{rules → rules-on-demand}/engineering/eng.bump-rules.md +0 -6
  52. package/rules-on-demand/engineering/eng.gate0-rules.md +56 -0
  53. package/rules-on-demand/engineering/eng.plan-rules.md +2 -49
  54. package/rules-on-demand/engineering/eng.pr-rules.md +29 -150
  55. package/rules-on-demand/engineering/eng.pre-pr-rules.md +5 -50
  56. package/{rules/engineering/rpa → rules-on-demand/engineering}/eng.rpa-rules.md +46 -10
  57. package/rules-on-demand/engineering/eng.security-rules.md +36 -0
  58. package/rules-on-demand/engineering/eng.start-rules.md +9 -3
  59. package/rules-on-demand/engineering/eng.tech-spec-rules.md +28 -473
  60. package/rules-on-demand/engineering/eng.transitions-rules.md +3 -1
  61. package/rules-on-demand/engineering/eng.work-rules.md +1 -48
  62. package/rules-on-demand/engineering/qa/eng.qa.cypress-standards-rules.md +259 -0
  63. package/rules-on-demand/product/prod.spec-common-rules.md +40 -0
  64. package/skills/AGENTS.md +12 -8
  65. package/skills/SKILLS-ROADMAP.md +16 -18
  66. package/skills/eng-ai/SKILL.md +5 -9
  67. package/skills/eng-automation/SKILL.md +7 -11
  68. package/skills/eng-backend/SKILL.md +4 -8
  69. package/skills/eng-backend-arch-c4/SKILL.md +18 -82
  70. package/skills/eng-backend-arch-c4/references/1-nivel-context.md +16 -0
  71. package/skills/eng-backend-arch-c4/references/2-nivel-container.md +17 -0
  72. package/skills/eng-backend-arch-c4/references/3-nivel-component.md +15 -0
  73. package/skills/eng-backend-arch-c4/references/4-nivel-code.md +12 -0
  74. package/skills/eng-backend-arch-c4/references/5-atualizacao-e-adrs.md +27 -0
  75. package/skills/eng-backend-microservices-trace/SKILL.md +4 -6
  76. package/skills/eng-backend-nestjs/SKILL.md +8 -57
  77. package/skills/eng-backend-nestjs/references/5-testes.md +13 -0
  78. package/skills/eng-backend-nestjs/references/6-problemas-comuns.md +37 -0
  79. package/skills/eng-data/SKILL.md +6 -10
  80. package/skills/eng-frontend/SKILL.md +6 -9
  81. package/skills/eng-global-branch/SKILL.md +124 -0
  82. package/skills/eng-global-docs-write/SKILL.md +1 -1
  83. package/skills/eng-global-investigation/SKILL.md +5 -6
  84. package/skills/eng-global-pr/SKILL.md +3 -17
  85. package/skills/eng-global-task-comment/SKILL.md +5 -2
  86. package/skills/eng-global-tech-spec/SKILL.md +4 -6
  87. package/skills/eng-global-tech-spec/references/delivery-spec.md +11 -179
  88. package/skills/eng-platform/SKILL.md +8 -14
  89. package/skills/eng-qa/SKILL.md +6 -11
  90. package/skills/eng-qa-planner/SKILL.md +0 -1
  91. package/skills/jarvis-context-detect/SKILL.md +29 -2
  92. package/skills/jarvis-context-detect/assets/context-profile-template.md +1 -1
  93. package/{templates → skills/jarvis-context-detect/references}/cdd-aplicado-a-prompts.md +1 -1
  94. package/skills/jarvis-context-detect/references/eng.work.md +28 -0
  95. package/skills/jarvis-create-specialization/SKILL.md +5 -9
  96. package/skills/jarvis-docs-central/README.md +22 -10
  97. package/skills/jarvis-docs-central/SKILL.md +78 -43
  98. package/skills/jarvis-docs-index/SKILL.md +1 -1
  99. package/skills/jarvis-evolution-architect/SKILL.md +1 -2
  100. package/skills/jarvis-fork/SKILL.md +6 -11
  101. package/skills/jarvis-init/SKILL.md +28 -370
  102. package/skills/jarvis-init/assets/exemplo-execucao.md +46 -0
  103. package/skills/jarvis-init/assets/mcp-configs.md +0 -91
  104. package/skills/jarvis-init/assets/rules-sync-manual.md +100 -0
  105. package/skills/jarvis-init/assets/setup-guide.md +0 -1
  106. package/skills/jarvis-init/assets/upgrade.md +51 -0
  107. package/skills/jarvis-init/assets/validacoes.md +56 -0
  108. package/skills/jarvis-list-specializations/SKILL.md +4 -8
  109. package/skills/jarvis-report-issue/SKILL.md +1 -2
  110. package/skills/product-roadmap-report/SKILL.md +3 -2
  111. package/skills/product-specs/SKILL.md +1 -3
  112. package/skills/product-specs-update/SKILL.md +0 -1
  113. package/templates/AGENTS.md +19 -3
  114. package/templates/ENV-template.md +0 -59
  115. package/templates/engineering/AGENTS-template.md +0 -1
  116. package/templates/engineering/breakdown-subtasks-template.md +76 -447
  117. package/templates/engineering/central-delivery-template.md +4 -1
  118. package/templates/engineering/central-feature-template.md +16 -7
  119. package/templates/engineering/central-home-template.md +31 -0
  120. package/templates/engineering/central-product-template.md +41 -0
  121. package/templates/engineering/data-contract-template.md +2 -2
  122. package/templates/engineering/light-arch-template.md +242 -0
  123. package/templates/engineering/qa/qa.test-coverage-report-template.md +62 -0
  124. package/templates/engineering/qa/qa.test-strategy-template.md +41 -0
  125. package/templates/engineering/qa/qa.test-suite-report-template.md +27 -0
  126. package/workflows/AGENTS.md +27 -36
  127. package/workflows/README.md +2 -11
  128. package/workflows/engineering/data/data.contract.md +2 -6
  129. package/workflows/engineering/data/data.new-pipeline.md +3 -7
  130. package/workflows/engineering/eng.breakdown-subtasks.md +9 -239
  131. package/workflows/engineering/eng.build-tech-spec.md +1 -3
  132. package/workflows/engineering/eng.create-ard-from-code.md +5 -6
  133. package/workflows/engineering/eng.create-ard.md +6 -10
  134. package/workflows/engineering/eng.create-rfc.md +4 -6
  135. package/workflows/engineering/eng.daily-report.md +0 -2
  136. package/workflows/engineering/eng.debug.md +1 -5
  137. package/workflows/engineering/eng.docs.md +2 -5
  138. package/workflows/engineering/eng.light-arch.md +7 -7
  139. package/workflows/engineering/eng.plan.md +2 -4
  140. package/workflows/engineering/eng.pr.md +9 -37
  141. package/workflows/engineering/eng.pre-pr.md +16 -8
  142. package/workflows/engineering/eng.review.md +1 -5
  143. package/workflows/engineering/eng.rpa.robot.md +5 -7
  144. package/workflows/engineering/eng.spec-consolidate.md +106 -42
  145. package/workflows/engineering/eng.start.md +16 -86
  146. package/workflows/engineering/eng.work.md +18 -151
  147. package/workflows/engineering/frontend/eng.frontend-component.md +1 -5
  148. package/workflows/engineering/frontend/eng.frontend-perf-audit.md +1 -4
  149. package/workflows/engineering/frontend/eng.frontend-review.md +1 -5
  150. package/workflows/engineering/qa/eng.qa-refinement-entry.md +0 -2
  151. package/workflows/engineering/qa/eng.qa-release-signoff.md +1 -4
  152. package/workflows/engineering/qa/eng.qa-sprint-planning.md +1 -5
  153. package/workflows/product/prod.roadmap.preview.md +0 -3
  154. package/workflows/product/prod.spec.ard.md +1 -4
  155. package/workflows/product/prod.spec.breakdown.md +4 -11
  156. package/workflows/product/prod.spec.clarify.md +1 -4
  157. package/workflows/product/prod.spec.discovery.md +2 -5
  158. package/workflows/product/prod.spec.epic.md +4 -18
  159. package/workflows/product/prod.spec.frd.md +5 -31
  160. package/workflows/product/prod.spec.issue.md +2 -3
  161. package/workflows/product/prod.spec.md +0 -3
  162. package/workflows/product/prod.spec.prd.md +6 -36
  163. package/workflows/warm-up.md +1 -4
  164. package/rules/AGENTS.md +0 -227
  165. package/rules/engineering/data/data-rules.md +0 -200
  166. package/rules/engineering/eng.docs-scraping-rules.md +0 -64
  167. package/rules/product/README.md +0 -27
  168. package/skills/eng-backend-rabbitmq/SKILL.md +0 -380
  169. package/skills/eng-backend-rabbitmq/references/1-referencia-endpoints.md +0 -28
  170. package/skills/eng-backend-rabbitmq/references/2-codigo-consumer-producer.md +0 -90
  171. package/skills/eng-backend-rabbitmq/references/3-arquiteturas-comuns.md +0 -101
  172. package/skills/eng-backend-rabbitmq/references/4-troubleshooting.md +0 -93
  173. package/skills/product-roadmap-report/rules/detailed-guide.md +0 -237
  174. package/templates/engineering/CONTACTS-template.md +0 -135
  175. package/templates/engineering/swagger-template.md +0 -145
  176. package/workflows/all-tools.md +0 -17
@@ -1,17 +1,15 @@
1
1
  /**
2
- * @fileoverview Gera o `{SQUAD}/index.md` do Central docs a partir do frontmatter
3
- * da consolidação (funcionalidades e entregas). O índice é sempre regenerado pela listagem (nunca editado), para
4
- * duas publicações seguidas não apagarem a entrada uma da outra.
2
+ * @fileoverview Gera o `{SQUAD}/index.md` do Central docs a partir da estrutura por
3
+ * funcionalidade (`{squad}/{produto}/{funcionalidade}/…`, seção 7 do `architecture.md`
4
+ * da #220). O índice é sempre regenerado pela listagem (nunca editado), para duas
5
+ * publicações seguidas não apagarem a entrada uma da outra.
5
6
  * @module docs/storage/build-index
6
7
  */
7
8
 
8
9
  import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
9
- import { join, relative, sep } from "node:path";
10
+ import { basename, join } from "node:path";
10
11
  import { parseFrontmatter } from "../../utils/frontmatter.js";
11
12
 
12
- /** @constant {ReadonlyArray<string>} Áreas do Central docs, na ordem do índice */
13
- export const AREAS = Object.freeze(["product", "engineering"]);
14
-
15
13
  /**
16
14
  * Lista arquivos (recursivo) de uma pasta, em ordem alfabética.
17
15
  * @param {string} dir
@@ -27,62 +25,100 @@ export function walkFiles(dir) {
27
25
  });
28
26
  }
29
27
 
30
- /** @constant {Readonly<Record<string, {prefix: string, title: string}>>} O que cada área lista no índice */
31
- export const INDEXED = Object.freeze({
32
- product: { prefix: "feature-", title: "Funcionalidades (estado atual)" },
33
- engineering: { prefix: "delivery-", title: "Entregas recentes" },
34
- });
28
+ function listDirs(dir) {
29
+ if (!existsSync(dir)) return [];
30
+ return readdirSync(dir)
31
+ .filter((name) => statSync(join(dir, name)).isDirectory())
32
+ .sort();
33
+ }
34
+
35
+ function isMarkdown(path) {
36
+ return path.endsWith(".md") && !path.endsWith(".public.md");
37
+ }
35
38
 
36
- /** @constant {number} Entregas listadas por produto (as mais recentes; o nome começa pela data) */
39
+ /** @constant {number} Entregas listadas por produto (as mais recentes) */
37
40
  export const MAX_DELIVERIES_PER_PRODUCT = 10;
38
41
 
39
42
  /**
40
- * Monta o conteúdo do índice de um squad. Lista só a consolidação do
41
- * `/eng.spec-consolidate`: funcionalidades (`feature-*`) e as entregas mais recentes
42
- * (`delivery-*`). Outros arquivos (ex.: PRD/ARD publicados na 4.0.0) ficam fora.
43
- * Formato: `# SQUAD` › `## área` › `### produto` › `- [arquivo](caminho) | status | nome | atualizado`.
43
+ * Monta o conteúdo do índice de um squad: a página de cada produto, as funcionalidades
44
+ * consolidadas (uma página por `feature-*`, publicada em `{funcionalidade}/{funcionalidade}.md`)
45
+ * e as entregas mais recentes de cada produto (`{funcionalidade}/deliveries/delivery-*.md`,
46
+ * deduplicadas por `task_key` — uma entrega quebrada em partes, Q9, cita o mesmo `task_key`
47
+ * em mais de uma funcionalidade). `archive/`, `decisions/`, `history/` e `home.md` ficam fora:
48
+ * não são o que foi implementado.
44
49
  * @param {string} root - Pasta do Central docs
45
50
  * @param {string} squad
46
51
  * @returns {string}
47
52
  */
48
53
  export function renderIndex(root, squad) {
54
+ const squadDir = join(root, squad);
49
55
  const out = [`# ${squad}`, ""];
50
56
 
51
- for (const area of AREAS) {
52
- const { prefix, title } = INDEXED[area];
53
- const areaDir = join(root, squad, area);
54
- const files = walkFiles(areaDir).filter((f) => {
55
- const name = f.split(sep).pop();
56
- // {nome}.public.md (versão humanizada, ARTIFACT_STYLE=human-generated) não entra no índice
57
- return name.startsWith(prefix) && name.endsWith(".md") && !name.endsWith(".public.md");
58
- });
59
- out.push(`## ${area}`, "", `> ${title}`, "");
60
- if (files.length === 0) {
61
- out.push("_Nenhum documento._", "");
62
- continue;
57
+ // `product`/`engineering`: nomes do layout antigo (pré-#220); se a migração não removeu as
58
+ // pastas vazias (ou ainda não rodou), não tratá-las como produto evita "## product"/
59
+ // "## engineering" vazios no índice (#220 item 9).
60
+ const products = listDirs(squadDir).filter((name) => name !== "product" && name !== "engineering");
61
+ if (products.length === 0) {
62
+ out.push("_Nenhum documento._", "");
63
+ return out.join("\n").replace(/\n+$/, "\n");
64
+ }
65
+
66
+ for (const product of products) {
67
+ const productDir = join(squadDir, product);
68
+ out.push(`## ${product}`, "");
69
+
70
+ const productPage = join(productDir, `${product}.md`);
71
+ if (existsSync(productPage)) {
72
+ const meta = parseFrontmatter(readFileSync(productPage, "utf-8"));
73
+ out.push(`> [${meta.name || "Visão do produto"}](${product}/${product}.md)`, "");
63
74
  }
64
75
 
65
- const byProduct = new Map();
66
- for (const file of files) {
67
- const [product = "", ...rest] = relative(areaDir, file).split(sep);
68
- if (rest.length === 0) continue; // arquivo solto na área, sem pasta de produto
69
- if (!byProduct.has(product)) byProduct.set(product, []);
70
- byProduct.get(product).push(file);
76
+ const features = listDirs(productDir).filter((name) => name !== "history");
77
+ const deliveries = [];
78
+
79
+ if (features.length === 0) {
80
+ out.push("_Nenhuma funcionalidade consolidada._", "");
81
+ continue;
71
82
  }
72
83
 
73
- for (const [product, productFiles] of byProduct) {
74
- const listed =
75
- area === "engineering"
76
- ? [...productFiles].sort().reverse().slice(0, MAX_DELIVERIES_PER_PRODUCT)
77
- : productFiles;
78
- out.push(`### ${product}`);
79
- for (const file of listed) {
80
- const rel = relative(join(root, squad), file).split(sep).join("/");
81
- const name = rel.split("/").pop();
84
+ for (const feature of features) {
85
+ const featureDir = join(productDir, feature);
86
+ const featurePage = join(featureDir, `${feature}.md`);
87
+ if (!existsSync(featurePage)) continue; // pasta sem a página (ex.: só archive/, ainda não publicada)
88
+
89
+ const meta = parseFrontmatter(readFileSync(featurePage, "utf-8"));
90
+ let line = `- [${feature}](${product}/${feature}/${feature}.md)`;
91
+ if (meta.status) line += ` | ${meta.status}`;
92
+ if (meta.name) line += ` | ${meta.name}`;
93
+ if (meta.updated_at) line += ` | ${meta.updated_at}`;
94
+ out.push(line);
95
+
96
+ for (const file of walkFiles(join(featureDir, "deliveries")).filter(isMarkdown)) {
82
97
  const meta = parseFrontmatter(readFileSync(file, "utf-8"));
83
- let line = `- [${name}](${rel})`;
84
- if (meta.status) line += ` | ${meta.status}`;
85
- if (meta.name) line += ` | ${meta.name}`;
98
+ deliveries.push({ feature, file, meta });
99
+ }
100
+ }
101
+ out.push("");
102
+
103
+ if (deliveries.length > 0) {
104
+ // Mais recente primeiro pela data; empate (mesmo task_key quebrado em partes, Q9) por nome.
105
+ const sorted = [...deliveries].sort((a, b) => {
106
+ const dateA = a.meta.updated_at || a.meta.date || "";
107
+ const dateB = b.meta.updated_at || b.meta.date || "";
108
+ if (dateA !== dateB) return dateB.localeCompare(dateA);
109
+ return basename(a.file).localeCompare(basename(b.file));
110
+ });
111
+ const byKey = new Map();
112
+ for (const d of sorted) {
113
+ const key = d.meta.task_key || d.file; // sem task_key, cada arquivo conta por si
114
+ if (!byKey.has(key)) byKey.set(key, d);
115
+ }
116
+
117
+ const recent = [...byKey.values()].slice(0, MAX_DELIVERIES_PER_PRODUCT);
118
+ out.push("> Entregas recentes", "");
119
+ for (const { feature, file, meta } of recent) {
120
+ const name = basename(file);
121
+ let line = `- [${name}](${product}/${feature}/deliveries/${name})`;
86
122
  if (meta.task_key) line += ` | ${meta.task_key}`;
87
123
  const when = meta.updated_at || meta.date;
88
124
  if (when) line += ` | ${when}`;
@@ -10,11 +10,13 @@
10
10
  */
11
11
 
12
12
  import { execFileSync } from "node:child_process";
13
- import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
13
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
14
14
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  import { createMergeRequest as defaultCreateMergeRequest, newMergeRequestUrl } from "../../vcs/api.js";
16
16
  import { logger } from "../../utils/logger.js";
17
17
  import { buildIndex, walkFiles } from "./build-index.js";
18
+ import { archiveEntries } from "../finish-delivery.js";
19
+ import { planCentralMigration, applyCentralMigration } from "../migrate-central.js";
18
20
 
19
21
  /**
20
22
  * Executa `git` na pasta informada, sem shell.
@@ -49,12 +51,62 @@ export function safePath(root, rel) {
49
51
  return full;
50
52
  }
51
53
 
54
+ /**
55
+ * `true` se não há nada staged para commitar (#220, rodada 2 item 2, N6): rodar de novo a
56
+ * publicação/arquivamento/migração de um conteúdo já idêntico ao que está em `targetBranch`
57
+ * (ex.: depois do PR anterior já ter sido mergeado) copiava os mesmos bytes, `git add` não
58
+ * marcava nada como alterado, e o `git commit` seguinte quebrava com "nothing to commit" em
59
+ * vez de ser um no-op.
60
+ * @param {(args: string[], cwd: string) => string} git
61
+ * @param {string} cwd
62
+ * @returns {boolean}
63
+ */
64
+ function nothingStaged(git, cwd) {
65
+ try {
66
+ git(["diff", "--cached", "--quiet"], cwd);
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Limpeza best-effort de uma branch de trabalho (#220, rodada 2 item 3): quando a cópia de um
75
+ * lote falha antes do primeiro commit (ex.: `localFile` que não existe mais no meio do lote),
76
+ * o arquivo já copiado fica untracked na working tree, e a branch criada por `checkout -B`
77
+ * nunca mais é referenciada — lixo que se acumula a cada falha, numa cópia persistente do
78
+ * Central docs. Só age quando a branch está **sem nenhum commit** além de `targetBranch` (0
79
+ * ahead): com commit, pode não ter sido empurrado ainda, e apagar a branch local perderia o
80
+ * único lugar onde ele existe — nesse caso, mantém o comportamento de sempre (branch fica).
81
+ * @param {(args: string[], cwd: string) => string} git
82
+ * @param {string} cwd
83
+ * @param {string} targetBranch
84
+ * @param {string} branch
85
+ * @param {string[]} candidatePaths - Destinos que o lote tentou copiar, para remover se tiverem
86
+ * ficado untracked (caminhos relativos a `cwd`)
87
+ */
88
+ function cleanupOrphanBranch(git, cwd, targetBranch, branch, candidatePaths) {
89
+ try {
90
+ const ahead = git(["rev-list", "--count", `${targetBranch}..${branch}`], cwd).trim();
91
+ if (ahead !== "0") return; // pode ter commit não empurrado: não apaga
92
+ git(["branch", "-D", branch], cwd);
93
+ for (const p of candidatePaths) {
94
+ try {
95
+ if (existsSync(join(cwd, p))) unlinkSync(join(cwd, p));
96
+ } catch {
97
+ // melhor esforço; não é o erro original
98
+ }
99
+ }
100
+ } catch {
101
+ // melhor esforço; nunca sobrepõe o erro original
102
+ }
103
+ }
104
+
52
105
  /**
53
106
  * @param {Object} cfg
54
107
  * @param {string} cfg.location - Pasta do Central docs (absoluta)
55
108
  * @param {string} [cfg.ref] - Branch lida no `pull` (CENTRAL_DOCS_REF)
56
109
  * @param {string} [cfg.targetBranch] - Branch base do PR (CENTRAL_DOCS_TARGET_BRANCH)
57
- * @param {string} [cfg.reviewers] - Revisores (vão na descrição do PR)
58
110
  * @param {Object} [cfg.deps] - `runGit` e `createMergeRequest` injetáveis (testes); `fileEnvResult`:
59
111
  * o ENV.md já lido pelo comando, repassado ao gate do `VERSION_CONTROL_ACCESS` no MR
60
112
  */
@@ -62,7 +114,6 @@ export function createFilesystemStorage({
62
114
  location,
63
115
  ref = "main",
64
116
  targetBranch = "main",
65
- reviewers = "",
66
117
  deps = {},
67
118
  }) {
68
119
  const git = deps.runGit ?? runGit;
@@ -156,6 +207,12 @@ export function createFilesystemStorage({
156
207
  ensureLocation();
157
208
  const dest = safePath(location, destPath);
158
209
 
210
+ // home.md é editado por pessoas: o adaptador cria uma vez e nunca sobrescreve (Q16, #220).
211
+ if (tipo === "home" && existsSync(dest)) {
212
+ logger.info(`ℹ️ ${destPath} já existe; a página inicial não é sobrescrita.`);
213
+ return { destPath, indexPath: `${squad}/index.md`, skipped: true };
214
+ }
215
+
159
216
  if (!isGit) {
160
217
  mkdirSync(dirname(dest), { recursive: true });
161
218
  copyFileSync(localFile, dest);
@@ -170,7 +227,7 @@ export function createFilesystemStorage({
170
227
  } catch (error) {
171
228
  logger.warn(`⚠️ git pull falhou (${error.message.split("\n")[0]}); seguindo com a cópia local.`);
172
229
  }
173
- git(["checkout", "-b", branch], location);
230
+ git(["checkout", "-B", branch, targetBranch], location);
174
231
 
175
232
  try {
176
233
  mkdirSync(dirname(dest), { recursive: true });
@@ -182,8 +239,7 @@ export function createFilesystemStorage({
182
239
 
183
240
  git(["push", "-u", "origin", branch], location);
184
241
  const remoteUrl = git(["remote", "get-url", "origin"], location);
185
- let description = `## Documento\n\n- **Tipo**: ${tipo}\n- **Arquivo**: \`${destPath}\``;
186
- if (reviewers) description += `\n- **Revisores**: ${reviewers}`;
242
+ const description = `## Documento\n\n- **Tipo**: ${tipo}\n- **Arquivo**: \`${destPath}\``;
187
243
  let mr = null;
188
244
  try {
189
245
  // O ENV.md que o comando já leu (com --ide/--env-file) vai junto para o gate do acesso.
@@ -222,5 +278,284 @@ export function createFilesystemStorage({
222
278
  }
223
279
  }
224
280
  },
281
+
282
+ /**
283
+ * Publica vários arquivos de uma vez (a consolidação de uma entrega, #220): cada um é
284
+ * copiado, o índice é regenerado **uma vez** no fim e, com `.git`, tudo entra numa **branch
285
+ * e um PR só** para a entrega inteira — não um por arquivo.
286
+ * @param {Object} p
287
+ * @param {Array<{localFile: string, destPath: string, tipo: string}>} p.files
288
+ * @param {string} p.squad
289
+ * @param {string} [p.slug] - Nome da branch/commit (ex.: a chave da entrega); padrão: a hora
290
+ * @returns {Promise<{ published: Array<{destPath: string, skipped?: boolean}>, indexPath: string, sha?: string, branch?: string, mr?: Object }>}
291
+ */
292
+ async publishBatch({ files, squad, slug }) {
293
+ ensureLocation();
294
+
295
+ const copyAll = () => {
296
+ const published = [];
297
+ for (const f of files) {
298
+ const dest = safePath(location, f.destPath);
299
+ // home.md é editado por pessoas: criado uma vez, nunca sobrescrito (Q16, #220).
300
+ if (f.tipo === "home" && existsSync(dest)) {
301
+ published.push({ destPath: f.destPath, skipped: true });
302
+ continue;
303
+ }
304
+ mkdirSync(dirname(dest), { recursive: true });
305
+ copyFileSync(f.localFile, dest);
306
+ published.push({ destPath: f.destPath, skipped: false });
307
+ }
308
+ return published;
309
+ };
310
+
311
+ if (!isGit) {
312
+ const published = copyAll();
313
+ const indexPath = this.buildIndex(squad);
314
+ return { published, indexPath };
315
+ }
316
+
317
+ const branch = `docs/${squad.toLowerCase()}-${slug || Date.now()}`;
318
+ git(["checkout", targetBranch], location);
319
+ try {
320
+ git(["pull", "--ff-only", "origin", targetBranch], location);
321
+ } catch (error) {
322
+ logger.warn(`⚠️ git pull falhou (${error.message.split("\n")[0]}); seguindo com a cópia local.`);
323
+ }
324
+ // `-B` (não `-b`): idempotente — uma segunda tentativa com o mesmo slug (depois de falha
325
+ // no push/PR) reusa a branch, em vez de falhar com "branch já existe" (#220, item 12).
326
+ git(["checkout", "-B", branch, targetBranch], location);
327
+
328
+ try {
329
+ const published = copyAll();
330
+ const indexPath = this.buildIndex(squad);
331
+ const changed = published.filter((p) => !p.skipped).map((p) => p.destPath);
332
+ if (changed.length === 0) {
333
+ // Lote todo `skipped` (ex.: só home.md já existente): nada para commitar/publicar.
334
+ return { published, indexPath };
335
+ }
336
+ git(["add", "--", ...changed, indexPath], location);
337
+ if (nothingStaged(git, location)) {
338
+ // Conteúdo idêntico ao que já está em targetBranch (#220, N6): sem isso, o commit
339
+ // seguinte quebrava com "nothing to commit" em vez de ser um no-op.
340
+ return { published, indexPath };
341
+ }
342
+ git(["commit", "-m", `docs(${squad}): consolidação ${slug || ""}`.trim()], location);
343
+ const sha = git(["rev-parse", "HEAD"], location);
344
+
345
+ git(["push", "-u", "origin", branch], location);
346
+ const remoteUrl = git(["remote", "get-url", "origin"], location);
347
+ const description = `## Documentos\n\n${changed.map((d) => `- \`${d}\``).join("\n")}`;
348
+ let mr = null;
349
+ try {
350
+ mr = await createMergeRequest(
351
+ remoteUrl,
352
+ {
353
+ source: branch,
354
+ target: targetBranch,
355
+ title: `docs(${squad}): consolidação ${slug || ""}`.trim(),
356
+ description,
357
+ },
358
+ deps.fileEnvResult ? { fileEnvResult: deps.fileEnvResult } : {}
359
+ );
360
+ } catch (error) {
361
+ if (error.sent) throw error;
362
+ let link = "";
363
+ try {
364
+ link = newMergeRequestUrl(remoteUrl, branch, targetBranch);
365
+ } catch {
366
+ // remote fora de github/gitlab: sem link
367
+ }
368
+ logger.warn(
369
+ `⚠️ MR não aberto (${error.message.split("\n")[0]}). A branch ${branch} já está no remote` +
370
+ (link ? `; abra o MR à mão: ${link}` : "; abra o MR à mão no host.")
371
+ );
372
+ }
373
+
374
+ return { published, indexPath, sha, branch, mr };
375
+ } finally {
376
+ try {
377
+ git(["checkout", targetBranch], location);
378
+ cleanupOrphanBranch(git, location, targetBranch, branch, files.map((f) => f.destPath));
379
+ } catch {
380
+ // a branch de trabalho fica; o erro original (se houver) é o que importa
381
+ }
382
+ }
383
+ },
384
+
385
+ /**
386
+ * Passo `--archive` (#220, Q3/Q14): copia os originais ligados a uma entrega para
387
+ * `archive/`, sem apagar nada. Sem `.git`, é a mesma cópia local de sempre — a pessoa
388
+ * já é avisada (no comando) de que `archive/` é a única proteção. **Com** `.git`, a
389
+ * cópia entra numa branch e PR próprios, como o `publishBatch`: sem isso, a promessa
390
+ * de "arquivar antes de apagar" das Q3/Q14 não valia — o arquivo ficava solto na cópia
391
+ * local de quem rodou o comando, nunca chegava ao remote (item 2, gate de código).
392
+ * @param {Object} p
393
+ * @param {string} p.squad
394
+ * @param {string} p.produto
395
+ * @param {Array<Object>} p.entries - Entradas do manifesto (mutadas com `archiveDestPath`/`archivedHash`)
396
+ * @returns {Promise<{archived: Array, skipped: Array, errors: string[], sha?: string, branch?: string, mr?: Object}>}
397
+ */
398
+ async archiveBatch({ squad, produto, entries }) {
399
+ ensureLocation();
400
+
401
+ if (!isGit) {
402
+ return archiveEntries({ root: location, squad, produto, entries });
403
+ }
404
+
405
+ const branch = `docs/${squad.toLowerCase()}-archive-${Date.now()}`;
406
+ git(["checkout", targetBranch], location);
407
+ try {
408
+ git(["pull", "--ff-only", "origin", targetBranch], location);
409
+ } catch (error) {
410
+ logger.warn(`⚠️ git pull falhou (${error.message.split("\n")[0]}); seguindo com a cópia local.`);
411
+ }
412
+ git(["checkout", "-B", branch, targetBranch], location);
413
+
414
+ let archivedPaths = [];
415
+ try {
416
+ const result = archiveEntries({ root: location, squad, produto, entries });
417
+ const changed = result.archived.map((a) => a.archiveDestPath);
418
+ archivedPaths = changed;
419
+ if (changed.length === 0) {
420
+ return result;
421
+ }
422
+ git(["add", "--", ...changed], location);
423
+ if (nothingStaged(git, location)) {
424
+ return result; // conteúdo idêntico ao que já está em targetBranch (#220, N6)
425
+ }
426
+ git(["commit", "-m", `docs(${squad}): arquiva ${changed.length} documento(s) de trabalho`], location);
427
+ const sha = git(["rev-parse", "HEAD"], location);
428
+
429
+ git(["push", "-u", "origin", branch], location);
430
+ const remoteUrl = git(["remote", "get-url", "origin"], location);
431
+ const description = `## Arquivamento\n\n${changed.map((d) => `- \`${d}\``).join("\n")}`;
432
+ let mr = null;
433
+ try {
434
+ mr = await createMergeRequest(
435
+ remoteUrl,
436
+ {
437
+ source: branch,
438
+ target: targetBranch,
439
+ title: `docs(${squad}): arquivamento de ${changed.length} documento(s)`,
440
+ description,
441
+ },
442
+ deps.fileEnvResult ? { fileEnvResult: deps.fileEnvResult } : {}
443
+ );
444
+ } catch (error) {
445
+ if (error.sent) throw error;
446
+ let link = "";
447
+ try {
448
+ link = newMergeRequestUrl(remoteUrl, branch, targetBranch);
449
+ } catch {
450
+ // remote fora de github/gitlab: sem link
451
+ }
452
+ logger.warn(
453
+ `⚠️ MR não aberto (${error.message.split("\n")[0]}). A branch ${branch} já está no remote` +
454
+ (link ? `; abra o MR à mão: ${link}` : "; abra o MR à mão no host.")
455
+ );
456
+ }
457
+
458
+ return { ...result, sha, branch, mr };
459
+ } finally {
460
+ try {
461
+ git(["checkout", targetBranch], location);
462
+ cleanupOrphanBranch(git, location, targetBranch, branch, archivedPaths);
463
+ } catch {
464
+ // a branch de trabalho fica; o erro original (se houver) é o que importa
465
+ }
466
+ }
467
+ },
468
+
469
+ /**
470
+ * `jarvis docs migrate --apply` (#220, Q2/Q6): move o layout antigo para a estrutura por
471
+ * funcionalidade. Sem `.git`, aplica direto na cópia local (como sempre, com o `plan` já
472
+ * calculado pelo chamador, para o dry-run mostrar o mesmo plano). **Com** `.git`, entra numa
473
+ * branch e PR próprios — sem isso, a migração mexia na cópia local, na branch em que ela
474
+ * estivesse, sem `pull` antes, podendo misturar a migração com a branch de outro PR (#220
475
+ * item 2, gate de código). Nesse caso, o plano é **recalculado depois do `pull`** (não usa
476
+ * o `plan` recebido): a árvore pode ter mudado desde o dry-run, e um plano desatualizado
477
+ * levaria a mover arquivo que não existe mais ou a não detectar um conflito novo (rodada 2,
478
+ * N4). O índice entra no mesmo commit da migração, não fica de fora.
479
+ * @param {Object} p
480
+ * @param {{moves: Array<{from: string, to: string}>}} p.plan - De `planCentralMigration` (usado só sem `.git`)
481
+ * @param {string} p.squad - Para recalcular o plano depois do `pull` (só com `.git`)
482
+ * @param {string} [p.timestamp] - Para o nome da pasta de backup (testável)
483
+ * @returns {Promise<{moved: Array, backupDir: string, errors: string[], sha?: string, branch?: string, mr?: Object}>}
484
+ */
485
+ async migrateApply({ plan, squad, timestamp }) {
486
+ ensureLocation();
487
+
488
+ if (!isGit) {
489
+ return applyCentralMigration(location, plan, timestamp);
490
+ }
491
+
492
+ const branch = `docs/migracao-${timestamp || Date.now()}`;
493
+ git(["checkout", targetBranch], location);
494
+ try {
495
+ git(["pull", "--ff-only", "origin", targetBranch], location);
496
+ } catch (error) {
497
+ logger.warn(`⚠️ git pull falhou (${error.message.split("\n")[0]}); seguindo com a cópia local.`);
498
+ }
499
+ git(["checkout", "-B", branch, targetBranch], location);
500
+
501
+ try {
502
+ const freshPlan = planCentralMigration(location, squad);
503
+ const result = applyCentralMigration(location, freshPlan, timestamp);
504
+ if (result.moved.length === 0) {
505
+ return result;
506
+ }
507
+ const indexPath = this.buildIndex(squad);
508
+ const paths = [...result.moved.flatMap((m) => [m.from, m.to]), indexPath];
509
+ if (existsSync(join(location, ".gitignore"))) paths.push(".gitignore");
510
+ // `-A` com pathspec: cobre a remoção do `from` (já movido pelo `rename`) e a adição do
511
+ // `to`/índice, limitado só a esses caminhos — não é um `git add -A` geral.
512
+ git(["add", "-A", "--", ...paths], location);
513
+ if (nothingStaged(git, location)) {
514
+ return result; // conteúdo idêntico ao que já está em targetBranch (#220, N6)
515
+ }
516
+ git(["commit", "-m", `docs: migra Central docs para a estrutura por funcionalidade (${result.moved.length} documento(s))`], location);
517
+ const sha = git(["rev-parse", "HEAD"], location);
518
+
519
+ git(["push", "-u", "origin", branch], location);
520
+ const remoteUrl = git(["remote", "get-url", "origin"], location);
521
+ const description = `## Migração\n\n${result.moved.length} documento(s) movido(s) para a estrutura por funcionalidade.\nCópia de segurança: \`${result.backupDir}\`.`;
522
+ let mr = null;
523
+ try {
524
+ mr = await createMergeRequest(
525
+ remoteUrl,
526
+ {
527
+ source: branch,
528
+ target: targetBranch,
529
+ title: `docs: migração do Central docs (#220)`,
530
+ description,
531
+ },
532
+ deps.fileEnvResult ? { fileEnvResult: deps.fileEnvResult } : {}
533
+ );
534
+ } catch (error) {
535
+ if (error.sent) throw error;
536
+ let link = "";
537
+ try {
538
+ link = newMergeRequestUrl(remoteUrl, branch, targetBranch);
539
+ } catch {
540
+ // remote fora de github/gitlab: sem link
541
+ }
542
+ logger.warn(
543
+ `⚠️ MR não aberto (${error.message.split("\n")[0]}). A branch ${branch} já está no remote` +
544
+ (link ? `; abra o MR à mão: ${link}` : "; abra o MR à mão no host.")
545
+ );
546
+ }
547
+
548
+ return { ...result, sha, branch, mr };
549
+ } finally {
550
+ try {
551
+ git(["checkout", targetBranch], location);
552
+ // Só apaga a branch órfã, sem remover arquivo nenhum: aqui são `rename`s, não cópias
553
+ // novas — tentar "limpar" um arquivo movido arriscaria apagar conteúdo de verdade.
554
+ cleanupOrphanBranch(git, location, targetBranch, branch, []);
555
+ } catch {
556
+ // a branch de trabalho fica; o erro original (se houver) é o que importa
557
+ }
558
+ }
559
+ },
225
560
  };
226
561
  }
@@ -69,7 +69,6 @@ export function getStorage(env, { root, deps } = {}) {
69
69
  location: resolveLocation(env.CENTRAL_DOCS_LOCATION, root),
70
70
  ref: env.CENTRAL_DOCS_REF || "main",
71
71
  targetBranch: env.CENTRAL_DOCS_TARGET_BRANCH || "main",
72
- reviewers: env.CENTRAL_DOCS_REVIEWERS || "",
73
72
  deps,
74
73
  });
75
74
  }
@@ -14,6 +14,13 @@ export function validateFrontmatter(filePath, tipo) {
14
14
  const content = readFileSync(filePath, 'utf-8')
15
15
 
16
16
  const frontmatter = extractFrontmatterBlock(content)
17
+ const requiredFields = getRequiredFields(tipo)
18
+
19
+ // Tipo sem campo obrigatório (ex.: swagger, um YAML/JSON sem a cerca `---`/`---` de frontmatter):
20
+ // sem frontmatter para exigir, não há o que validar.
21
+ if (frontmatter === null && requiredFields.length === 0) {
22
+ return {}
23
+ }
17
24
 
18
25
  if (frontmatter === null) {
19
26
  throw new Error(
@@ -29,7 +36,6 @@ export function validateFrontmatter(filePath, tipo) {
29
36
  const metadata = parseFrontmatter(content)
30
37
 
31
38
  // Validar campos obrigatórios por tipo
32
- const requiredFields = getRequiredFields(tipo)
33
39
  const missingFields = []
34
40
 
35
41
  for (const field of requiredFields) {
@@ -71,6 +77,25 @@ export function validateFrontmatter(filePath, tipo) {
71
77
  )
72
78
  }
73
79
 
80
+ // Labels no padrão Confluence (Q2 da #220): minúsculas, letras/números/hífen, sem espaço.
81
+ // Opcional — documento antigo sem o campo continua válido (Q6: a migração não inventa labels).
82
+ if (metadata.labels) {
83
+ // Sintaxe de lista YAML (`{a, b}` ou `[a, b]`, #220 item 13): tira os colchetes/chaves
84
+ // antes de separar por vírgula, senão o primeiro e o último label ficam presos a eles e
85
+ // a mensagem de erro aponta "label" inválido mesmo quando todos estão certos.
86
+ const semColchetes = metadata.labels.replace(/^[{[]/, '').replace(/[}\]]$/, '')
87
+ const invalidas = semColchetes
88
+ .split(',')
89
+ .map((l) => l.trim())
90
+ .filter((l) => l && !/^[a-z0-9][a-z0-9-]*$/.test(l))
91
+ if (invalidas.length > 0) {
92
+ throw new Error(
93
+ `Labels fora do padrão em ${filePath}: ${invalidas.join(', ')}\n` +
94
+ 'Use minúsculas, números e hífen, sem espaço (ex.: arquitetura, decisao).'
95
+ )
96
+ }
97
+ }
98
+
74
99
  return metadata
75
100
  }
76
101
 
@@ -85,7 +110,11 @@ function getRequiredFields(tipo) {
85
110
  // Consolidação do Central docs (/eng.spec-consolidate)
86
111
  feature: ['id', 'name', 'status', 'product', 'updated_at'],
87
112
  delivery: ['id', 'feature', 'task_key', 'pr', 'date'],
88
- // Documentos de trabalho (validação usada fora do publish)
113
+ // Central docs: página do produto (transversal, Q22) e página inicial do squad (Q16)
114
+ product: ['id', 'name', 'updated_at'],
115
+ home: ['name'],
116
+ // Documentos de trabalho (validação usada fora do publish; os mesmos tipos, agora também
117
+ // publicáveis em decisions/ quando ligados a uma entrega consolidada — Q1, Q9, Q10 da #220)
89
118
  prd: ['id', 'name', 'version', 'status'],
90
119
  frd: ['id', 'name', 'version', 'status', 'related_prd'],
91
120
  feat: ['id', 'name', 'version', 'status', 'related_prd'],
@@ -94,7 +123,10 @@ function getRequiredFields(tipo) {
94
123
  task: ['id', 'name', 'status'],
95
124
  ard: ['id', 'name', 'version', 'status'],
96
125
  rfc: ['Status', 'Criado em', 'Proponente'],
126
+ discovery: ['id', 'name', 'status'],
97
127
  'qa-report': ['period', 'squad', 'version']
128
+ // swagger e history: sem campo obrigatório — swagger pode ser um YAML/JSON sem a cerca de
129
+ // frontmatter; history (gate-checklist.md, daily.md, task-comment-*.md) tem formato próprio.
98
130
  }
99
131
 
100
132
  return fields[tipo] || []