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
@@ -0,0 +1,107 @@
1
+ import { openStorageFromEnv } from "../lib/docs/fetch-file.js";
2
+ import { planCentralMigration } from "../lib/docs/migrate-central.js";
3
+ import { assertSegment } from "../lib/docs/publish-file.js";
4
+ import { logger, configureFromFlags } from "../lib/utils/logger.js";
5
+
6
+ /**
7
+ * Migra o Central docs do layout antigo ({squad}/product/{produto}/feature-*.md,
8
+ * {squad}/engineering/{produto}/delivery-*.md) para a estrutura por funcionalidade (#220).
9
+ * Dry-run por padrão: só mostra o plano. Com `--apply`, guarda uma cópia e move de verdade.
10
+ * Chamado pelo `/jarvis-init` (Upgrade C), que mostra o plano e pergunta antes de `--apply`
11
+ * (regra de ouro); rodar direto no terminal é equivalente, a pessoa decide na hora.
12
+ *
13
+ * @param {Object} flags
14
+ * @param {boolean} [flags.apply] - Aplica o plano; sem ela, só mostra (dry-run)
15
+ * @param {string} [flags.squad] - Override do SQUAD do ENV.md
16
+ * @param {string} flags.envFile - Path customizado do ENV.md
17
+ */
18
+ export async function docsMigrate(flags = {}) {
19
+ configureFromFlags(flags);
20
+
21
+ let env;
22
+ let storage;
23
+ try {
24
+ ({ env, storage } = openStorageFromEnv(flags));
25
+ } catch (error) {
26
+ logger.error("❌ Central docs:", error.message);
27
+ process.exit(1);
28
+ }
29
+
30
+ if (!storage) {
31
+ logger.error("❌ Central docs desligado (CENTRAL_DOCS_STORAGE vazio no ENV.md).");
32
+ process.exit(1);
33
+ }
34
+ if (storage.kind !== "filesystem") {
35
+ logger.error(
36
+ `❌ jarvis docs migrate só funciona com CENTRAL_DOCS_STORAGE=filesystem (acesso direto à pasta); este ENV.md usa "${storage.kind}".`
37
+ );
38
+ process.exit(1);
39
+ }
40
+
41
+ const squad = flags.squad || env.SQUAD;
42
+ if (!squad) {
43
+ logger.error("❌ SQUAD não definido no ENV.md (ou passe --squad <squad>)");
44
+ process.exit(1);
45
+ }
46
+ try {
47
+ // Sem isto, um squad errado (ou `--squad ../x`) chegava direto ao `join(root, squad, ...)`
48
+ // sem a mesma validação que `publish`/`archive` já fazem (#220 item 8).
49
+ assertSegment("Squad", squad);
50
+ } catch (error) {
51
+ logger.error(`❌ ${error.message}`);
52
+ process.exit(1);
53
+ }
54
+
55
+ const plan = planCentralMigration(storage.location, squad);
56
+
57
+ logger.info(`📦 Migração do Central docs — squad ${squad}`);
58
+ logger.info(` ${plan.moves.length} arquivo(s) para a estrutura por funcionalidade`);
59
+
60
+ if (plan.needsSplit.length > 0) {
61
+ logger.info(
62
+ ` ⚠️ ${plan.needsSplit.length} entrega(s) ligada(s) a mais de uma funcionalidade — não movida(s) automaticamente (a quebra, Q9/Q21 da #220, pede o agente):`
63
+ );
64
+ for (const s of plan.needsSplit) {
65
+ logger.info(` - ${s.delivery} → ${s.features.join(", ")}`);
66
+ }
67
+ }
68
+ if (plan.skipped.length > 0) {
69
+ logger.info(` ${plan.skipped.length} ignorado(s):`);
70
+ for (const s of plan.skipped) logger.info(` - ${s.from} (${s.reason})`);
71
+ }
72
+
73
+ if (!flags.apply) {
74
+ logger.debug("");
75
+ for (const m of plan.moves) logger.debug(` ${m.from} → ${m.to}`);
76
+ logger.info("\nDry-run: nada foi alterado. Rode de novo com --apply para mover de verdade.");
77
+ return;
78
+ }
79
+
80
+ if (plan.moves.length === 0) {
81
+ logger.info("\nNada para mover.");
82
+ return;
83
+ }
84
+
85
+ const result = await storage.migrateApply({ plan, squad });
86
+
87
+ logger.info(`\n✅ ${result.moved.length} arquivo(s) movido(s)`);
88
+ logger.info(`🗄️ Cópia dos originais em: ${result.backupDir}`);
89
+ if (result.branch) logger.info(`🌿 Branch: ${result.branch}`);
90
+ if (result.mr) logger.info(`🔀 Pull/Merge Request: ${result.mr.url}`);
91
+
92
+ // Com .git, o índice já foi regenerado e comitado dentro de migrateApply, na branch de
93
+ // trabalho (rodada 2, N4) — regenerá-lo aqui de novo rodaria na branch base, sem o que
94
+ // acabou de ser migrado. Sem .git, não há branch nenhuma: regenera direto na cópia local.
95
+ if (!storage.isGit) {
96
+ const indexPath = storage.buildIndex(squad);
97
+ logger.info(`🗂️ Índice regenerado: ${indexPath}`);
98
+ }
99
+
100
+ if (result.errors.length > 0) {
101
+ logger.error(`⚠️ ${result.errors.length} erro(s):`);
102
+ for (const e of result.errors) logger.error(` - ${e}`);
103
+ // #220 item 11: migração parcial não é sucesso — scripts que dependem do código de saída
104
+ // (ex.: /jarvis-init) não devem tratá-la como se tivesse ido tudo bem.
105
+ process.exit(1);
106
+ }
107
+ }
@@ -1,17 +1,93 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
2
3
  import { openStorageFromEnv } from "../lib/docs/fetch-file.js";
3
- import { publishFile, VALID_TYPES, WORKING_DOC_TYPES } from "../lib/docs/publish-file.js";
4
+ import { publishFile, publishFiles, VALID_TYPES } from "../lib/docs/publish-file.js";
5
+ import { forceFinalize } from "../lib/docs/finish-delivery.js";
4
6
  import { logger, configureFromFlags } from "../lib/utils/logger.js";
5
7
 
8
+ function openEnvAndStorage(flags) {
9
+ let env;
10
+ let storage;
11
+ let root;
12
+ try {
13
+ ({ env, storage, root } = openStorageFromEnv(flags));
14
+ } catch (error) {
15
+ logger.error("❌ Central docs:", error.message);
16
+ process.exit(1);
17
+ }
18
+ if (!storage) {
19
+ logger.error("❌ Central docs desligado (CENTRAL_DOCS_STORAGE vazio no ENV.md).");
20
+ logger.error(" Configure-o com o /jarvis-init.");
21
+ process.exit(1);
22
+ }
23
+ return { env, storage, root };
24
+ }
25
+
26
+ function resolveSquadProduto(flags, env) {
27
+ const squad = flags.squad || env.SQUAD;
28
+ const produto = flags.produto || flags.workspace || env.WORKSPACE;
29
+ if (!squad || !produto) {
30
+ logger.error("❌ SQUAD ou WORKSPACE não definidos");
31
+ logger.error(" Defina no ENV.md ou passe --squad <squad> --produto <produto>");
32
+ process.exit(1);
33
+ }
34
+ return { squad, produto };
35
+ }
36
+
37
+ function reportPublishError(error, storage, tipo) {
38
+ logger.error("\n❌ Erro ao publicar documento\n");
39
+ logger.error(error.message);
40
+ if (error.message.includes("Campos obrigatórios")) {
41
+ logger.error(`\n💡 Verifique o frontmatter do documento: o tipo ${tipo} exige campos específicos.`);
42
+ }
43
+ if (storage.isGit) {
44
+ logger.error(
45
+ "\n💡 Central docs com git: confira se a pasta está limpa (git status), se você tem permissão de push"
46
+ );
47
+ logger.error(" e se a CLI do host está logada (gh auth login, glab auth login).");
48
+ }
49
+ }
50
+
6
51
  /**
7
- * Publica um documento no Central docs pelo adaptador configurado.
52
+ * Lê um manifesto `[{file, tipo, feature?, taskKey?}, …]` (caminhos relativos à pasta do
53
+ * manifesto). Gerado pelo `/eng.spec-consolidate` a partir da listagem "move / fica" (#220).
54
+ */
55
+ function readManifest(path) {
56
+ if (!existsSync(path)) {
57
+ logger.error(`❌ Manifesto não encontrado: ${path}`);
58
+ process.exit(1);
59
+ }
60
+ let entries;
61
+ try {
62
+ entries = JSON.parse(readFileSync(path, "utf-8"));
63
+ } catch (error) {
64
+ logger.error(`❌ Manifesto inválido (${path}): ${error.message}`);
65
+ process.exit(1);
66
+ }
67
+ if (!Array.isArray(entries) || entries.length === 0) {
68
+ logger.error(`❌ Manifesto vazio ou no formato errado: ${path}`);
69
+ process.exit(1);
70
+ }
71
+ const base = dirname(path);
72
+ return entries.map(({ file, ...rest }) => ({ ...rest, localFile: join(base, file) }));
73
+ }
74
+
75
+ /**
76
+ * Publica no Central docs pelo adaptador configurado.
8
77
  * Sem `.git` na pasta: copia e regenera o índice. Com `.git`: branch, commit, push e PR.
9
78
  *
10
79
  * @param {Object} flags - Flags do comando
11
- * @param {string} flags.file - Caminho do arquivo local
12
- * @param {string} flags.tipo - feature | delivery (ver VALID_TYPES)
80
+ * @param {string} [flags.file] - Caminho do arquivo local (um só; alternativa ao `--manifest`)
81
+ * @param {string} [flags.tipo] - Ver VALID_TYPES (feature, delivery, product, history e os
82
+ * documentos de trabalho ligados a uma entrega consolidada)
83
+ * @param {string} [flags.manifest] - Caminho de um manifesto JSON com vários arquivos (publicação
84
+ * em lote: uma branch e um PR só, em vez de um por arquivo)
85
+ * @param {string} [flags.slug] - Nome da branch/commit do lote (ex.: a chave da entrega)
13
86
  * @param {string} [flags.produto] - Pasta do produto (padrão: WORKSPACE do ENV.md)
14
- * @param {string} [flags.feature] - Slug, só se o nome do arquivo fugir do padrão {tipo}-{nome}.md
87
+ * @param {string} [flags.feature] - Slug da funcionalidade. Opcional para `feature` quando o
88
+ * nome do arquivo segue `feature-{slug}.md`; obrigatório para `delivery` e para os
89
+ * documentos de trabalho (é a funcionalidade dona da pasta `decisions/`)
90
+ * @param {string} [flags.taskKey] - Obrigatório para `--tipo history`
15
91
  * @param {string} [flags.squad] - Override do SQUAD do ENV.md
16
92
  * @param {string} [flags.workspace] - Override do WORKSPACE (padrão do --produto)
17
93
  * @param {string} flags.envFile - Path customizado do ENV.md
@@ -19,37 +95,23 @@ import { logger, configureFromFlags } from "../lib/utils/logger.js";
19
95
  export async function docsPublish(flags = {}) {
20
96
  configureFromFlags(flags);
21
97
 
22
- const {
23
- file,
24
- tipo,
25
- feature,
26
- produto,
27
- squad: squadOverride,
28
- workspace: workspaceOverride,
29
- } = flags;
98
+ if (flags.manifest) {
99
+ return docsPublishManifest(flags);
100
+ }
101
+
102
+ const { file, tipo, feature, taskKey } = flags;
30
103
 
31
104
  if (!file || !tipo) {
32
105
  logger.error("❌ Parâmetros obrigatórios faltando\n");
33
106
  logger.error(
34
- `Uso: jarvis docs publish --file <path> --tipo <${VALID_TYPES.join("|")}> [--produto <produto>] [--feature <slug>] [--squad <squad>]\n`
35
- );
36
- logger.error(
37
- "Normalmente chamado pelo /eng.spec-consolidate, que gera os dois arquivos na sessão:"
38
- );
39
- logger.error(
40
- " jarvis docs publish --file .jarvis/sessions/eng/task-123/consolidation/delivery-2026-10-15-task-123.md --tipo delivery"
41
- );
42
- logger.error(
43
- " jarvis docs publish --file .jarvis/sessions/eng/task-123/consolidation/feature-checkout.md --tipo feature"
107
+ `Uso: jarvis docs publish --file <path> --tipo <${VALID_TYPES.join("|")}> [--produto <produto>] [--feature <slug>] [--task-key <chave>] [--squad <squad>]\n` +
108
+ " ou: jarvis docs publish --manifest <path> [--slug <chave>] (publicação em lote)\n"
44
109
  );
45
- process.exit(1);
46
- }
47
-
48
- if (WORKING_DOC_TYPES.includes(tipo)) {
110
+ logger.error("Normalmente chamado pelo /eng.spec-consolidate, que gera os arquivos na sessão:");
111
+ logger.error(" jarvis docs publish --file .../consolidation/feature-checkout.md --tipo feature");
49
112
  logger.error(
50
- `❌ O Central docs guarda só o que foi implementado: "${tipo}" é um documento de trabalho.`
113
+ " jarvis docs publish --file .../consolidation/delivery-2026-10-15-task-123.md --tipo delivery --feature checkout"
51
114
  );
52
- logger.error(" Ele fica em docs/jarvis/. Gere a consolidação com /eng.spec-consolidate.");
53
115
  process.exit(1);
54
116
  }
55
117
 
@@ -58,59 +120,62 @@ export async function docsPublish(flags = {}) {
58
120
  logger.error(`Tipos válidos: ${VALID_TYPES.join(", ")}`);
59
121
  process.exit(1);
60
122
  }
61
-
62
123
  if (!existsSync(file)) {
63
124
  logger.error(`❌ Arquivo não encontrado: ${file}`);
64
125
  process.exit(1);
65
126
  }
66
127
 
67
- let env;
68
- let storage;
128
+ const { env, storage } = openEnvAndStorage(flags);
129
+ const { squad, produto } = resolveSquadProduto(flags, env);
130
+
131
+ logger.info(`📤 Publicando ${tipo.toUpperCase()} (${file})...\n`);
132
+
69
133
  try {
70
- ({ env, storage } = openStorageFromEnv(flags));
134
+ await publishFile({ storage, localFile: file, tipo, squad, produto, feature, taskKey });
135
+ logger.info("");
136
+ logger.info("✅ Publicação concluída!");
71
137
  } catch (error) {
72
- logger.error("❌ Central docs:", error.message);
138
+ reportPublishError(error, storage, tipo);
73
139
  process.exit(1);
74
140
  }
141
+ }
75
142
 
76
- if (!storage) {
77
- logger.error("❌ Central docs desligado (CENTRAL_DOCS_STORAGE vazio no ENV.md).");
78
- logger.error(" Configure-o com o /jarvis-init.");
79
- process.exit(1);
80
- }
143
+ async function docsPublishManifest(flags) {
144
+ const files = readManifest(flags.manifest);
145
+ const { env, storage, root } = openEnvAndStorage(flags);
146
+ const { squad, produto } = resolveSquadProduto(flags, env);
81
147
 
82
- const squad = squadOverride || env.SQUAD;
83
- const product = produto || workspaceOverride || env.WORKSPACE;
84
-
85
- if (!squad || !product) {
86
- logger.error("❌ SQUAD ou WORKSPACE não definidos");
87
- logger.error(" Defina no ENV.md ou passe --squad <squad> --produto <produto>");
88
- process.exit(1);
89
- }
90
-
91
- logger.info(`📤 Publicando ${tipo.toUpperCase()} (${file})...\n`);
148
+ logger.info(`📤 Publicando a consolidação em lote (${files.length} arquivo(s))...\n`);
92
149
 
93
150
  try {
94
- await publishFile({ storage, localFile: file, tipo, squad, produto: product, feature });
151
+ await publishFiles({ storage, squad, produto, slug: flags.slug, files });
95
152
  logger.info("");
96
153
  logger.info("✅ Publicação concluída!");
97
154
  } catch (error) {
98
- logger.error("\n❌ Erro ao publicar documento\n");
99
- logger.error(error.message);
100
-
101
- if (error.message.includes("Campos obrigatórios")) {
102
- logger.error(
103
- `\n💡 Verifique o frontmatter do documento: o tipo ${tipo} exige campos específicos.`
104
- );
105
- }
106
- if (storage.isGit) {
107
- logger.error(
108
- "\n💡 Central docs com git: confira se a pasta está limpa (git status), se você tem permissão de push"
109
- );
110
- logger.error(
111
- " e se a CLI do host está logada (gh auth login, glab auth login)."
112
- );
113
- }
155
+ reportPublishError(error, storage, "lote");
156
+ process.exit(1);
157
+ }
158
+
159
+ if (!flags.force) return;
160
+
161
+ // --force (Q15, #220): publica e já apaga os originais, sem --archive. Zero reversão.
162
+ logger.info("\n⚠️ --force: finalizando sem arquivar (zero reversão)...");
163
+ const { finalized, rewritten, errors } = forceFinalize({
164
+ entries: files,
165
+ squad,
166
+ produto,
167
+ env,
168
+ workspaceRoot: root,
169
+ });
170
+ logger.info(`🧹 ${finalized.length} original(is) removido(s) (sem cópia em archive/)`);
171
+ for (const f of finalized) logger.info(` - ${f.originalPath}`);
172
+ if (rewritten.length > 0) {
173
+ logger.info(`🔗 ${rewritten.length} referência(s) (related_*) reescrita(s):`);
174
+ for (const r of rewritten) logger.info(` - ${r}`);
175
+ }
176
+ if (errors.length > 0) {
177
+ logger.error(`⚠️ ${errors.length} erro(s) ao finalizar:`);
178
+ for (const e of errors) logger.error(` - ${e}`);
114
179
  process.exit(1);
115
180
  }
116
181
  }
@@ -1,8 +1,12 @@
1
1
  import { openStorageFromEnv } from "../lib/docs/fetch-file.js";
2
2
  import { logger, configureFromFlags } from "../lib/utils/logger.js";
3
3
 
4
- const COUNTED_TYPES = ["feature", "delivery"];
5
- const LABELS = { feature: "funcionalidade(s)", delivery: "entrega(s) recente(s)" };
4
+ // Contagem pelo link que renderIndex gera (build-index.js): a página da funcionalidade
5
+ // termina em `/{slug}/{slug}.md`; a entrega mora em `/{slug}/deliveries/delivery-*.md`.
6
+ const COUNTED = [
7
+ ["feature", "funcionalidade(s)", /\]\(([a-z0-9_-]+)\/\1\/\1\.md\)/gi],
8
+ ["delivery", "entrega(s) recente(s)", /\]\([a-z0-9_-]+\/[a-z0-9_-]+\/deliveries\/delivery-[^)]*\.md\)/gi],
9
+ ];
6
10
 
7
11
  /**
8
12
  * Sincroniza a documentação do Central docs (lê `{SQUAD}/index.md` pelo adaptador).
@@ -48,15 +52,16 @@ export async function docsSync(flags = {}) {
48
52
  logger.debug("\n📄 Conteúdo do index.md:\n");
49
53
  logger.debug(content);
50
54
 
51
- const counts = COUNTED_TYPES.map((tipo) => [
55
+ const counts = COUNTED.map(([tipo, label, re]) => [
52
56
  tipo,
53
- (content.match(new RegExp(`\\[${tipo}-[^\\]]*\\]`, "g")) || []).length,
54
- ]).filter(([, n]) => n > 0);
55
- const total = counts.reduce((sum, [, n]) => sum + n, 0);
57
+ label,
58
+ (content.match(re) || []).length,
59
+ ]).filter(([, , n]) => n > 0);
60
+ const total = counts.reduce((sum, [, , n]) => sum + n, 0);
56
61
 
57
62
  if (total > 0) {
58
63
  logger.info(`📊 ${total} documentos disponíveis:`);
59
- for (const [tipo, n] of counts) logger.info(` - ${n} ${LABELS[tipo]}`);
64
+ for (const [, label, n] of counts) logger.info(` - ${n} ${label}`);
60
65
  }
61
66
  } catch (error) {
62
67
  logger.error("❌ Erro ao sincronizar docs:", error.message);
@@ -1,7 +1,12 @@
1
1
  import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { join, dirname, basename, resolve, sep } from "node:path";
3
3
  import { createInterface } from "node:readline";
4
- import { syncAssets, applyRuleOverlay } from "../lib/core/sync-engine.js";
4
+ import {
5
+ syncAssets,
6
+ applyRuleOverlay,
7
+ syncRulesForProfile,
8
+ rtkAvailable,
9
+ } from "../lib/core/sync-engine.js";
5
10
  import { discoverAll } from "../lib/core/scanner.js";
6
11
  import {
7
12
  IDES,
@@ -58,21 +63,75 @@ export function parseMenuChoice(answer, { hasEnv }) {
58
63
  return null;
59
64
  }
60
65
 
66
+ /** Eixos do perfil que o filtro de rules exige (o mesmo do `jarvis rules sync`). */
67
+ const PROFILE_AXES = ["HUB", "POSITION", "AREA", "SQUAD"];
68
+
69
+ /**
70
+ * Filtra `.{ide}/rules/` e `rules-on-demand/` pelo perfil do ENV.md, como o `jarvis rules sync`
71
+ * (#83). Usado no fim do `--upgrade` e da reinstalação, depois que o `syncAssets` copiou as rules
72
+ * inteiras. Sem os 4 eixos (vazios ou com o exemplo `[...]` do template), não filtra. A
73
+ * `rtk-rules.md` só entra com `RTK_ENABLED=true` e o `rtk` no PATH (o `reconcileRtk` a tira sem ele).
74
+ * @param {string} workspaceDir
75
+ * @param {string} ide
76
+ * @param {string} envPath
77
+ * @returns {{ rulesSync: ReturnType<typeof syncRulesForProfile> | null, missingProfile: string[], profileLabel: string }}
78
+ */
79
+ export function filterRulesByEnv(workspaceDir, ide, envPath) {
80
+ const envText = readFileSync(envPath, "utf-8");
81
+ const entries = parseEnvEntries(envText);
82
+ const value = (key) => {
83
+ const v = (entries.get(key) || "").trim();
84
+ return v && !/^\[.*\]$/.test(v) ? v : "";
85
+ };
86
+ const missingProfile = PROFILE_AXES.filter((axis) => !value(axis));
87
+ const profileLabel = PROFILE_AXES.map(value).join("/");
88
+ if (missingProfile.length) return { rulesSync: null, missingProfile, profileLabel };
89
+ const rulesSync = syncRulesForProfile(
90
+ join(workspaceDir, `.${getIDEFolder(ide)}`),
91
+ {
92
+ HUB: value("HUB"),
93
+ POSITION: value("POSITION"),
94
+ AREA: value("AREA"),
95
+ SQUAD: value("SQUAD"),
96
+ ARTIFACT_STYLE: value("ARTIFACT_STYLE") || "ai-generated",
97
+ },
98
+ { rtkEnabled: value("RTK_ENABLED") === "true" && rtkAvailable(), envText }
99
+ );
100
+ return { rulesSync, missingProfile, profileLabel };
101
+ }
102
+
103
+ /** Linha de resumo do filtro de rules, com avisos e erros (nada sem filtro). */
104
+ function logRulesFilter(rulesSync, profileLabel) {
105
+ if (!rulesSync) return;
106
+ const copied = rulesSync.copied.rules + rulesSync.copied["rules-on-demand"];
107
+ logger.info(
108
+ ` • Rules filtradas pelo perfil (${profileLabel}): ${copied} copiada(s), ${rulesSync.removed} removida(s)`
109
+ );
110
+ for (const w of rulesSync.warnings) logger.info(`${YELLOW} ⚠️ ${w}${NC}`);
111
+ for (const e of rulesSync.errors) logger.error(`${RED} ✗ ${e}${NC}`);
112
+ }
113
+
61
114
  /**
62
115
  * O que ainda pede o `/jarvis-init upgrade` na IDE depois do `jarvis init --upgrade` (#189, Q4).
63
116
  * Só as pendências que o terminal não resolve: eixo sem forma de acesso, chave vazia, Central docs
64
117
  * no formato antigo e TOKEN_TASK_MANAGER com valor. Não contam o aviso de WORKSPACE_MODE (conferir
65
118
  * no ENV.md), vendor não suportado (vira freelance) nem as chaves novas acrescentadas (Q15: o
66
119
  * `/jarvis-init` as põe no assunto delas na próxima vez que rodar). Nunca inclui valores do ENV.
67
- * @param {{ pendingAxes: string[], envPlan: { pending?: string[], warnings?: string[] } }} input
120
+ * Eixo do perfil vazio (HUB, POSITION, AREA, SQUAD) também conta: sem ele, o upgrade não filtra
121
+ * as rules (#83).
122
+ * @param {{ pendingAxes: string[], envPlan: { pending?: string[], warnings?: string[] }, missingProfile?: string[] }} input
68
123
  * @returns {string[]} um motivo por pendência; vazio = nada pendente
69
124
  */
70
- export function upgradePendencies({ pendingAxes, envPlan }) {
125
+ export function upgradePendencies({ pendingAxes, envPlan, missingProfile = [] }) {
71
126
  const reasons = [];
72
127
  if (pendingAxes.length) reasons.push(`confirmar o acesso de ${pendingAxes.join(" e ")}`);
128
+ if (missingProfile.length) {
129
+ reasons.push(`preencher ${missingProfile.join(", ")} (as rules ficam sem o filtro do perfil)`);
130
+ }
73
131
  if (envPlan.pending?.length) reasons.push(`preencher ${envPlan.pending.join(", ")}`);
74
132
  const warnings = envPlan.warnings || [];
75
133
  if (warnings.includes("CENTRAL_DOCS_REPO")) reasons.push("migrar o Central docs");
134
+ if (warnings.includes("CENTRAL_DOCS_LAYOUT")) reasons.push("migrar o Central docs para a estrutura por funcionalidade");
76
135
  if (warnings.includes("TOKEN_TASK_MANAGER")) reasons.push("remover o TOKEN_TASK_MANAGER");
77
136
  return reasons;
78
137
  }
@@ -335,6 +394,14 @@ export async function init(flags) {
335
394
  for (const item of result.errors) {
336
395
  logger.error(`${RED} ✗ ${item}${NC}`);
337
396
  }
397
+ // Reinstalação com o ENV.md preenchido: o mesmo filtro do --upgrade (#83). Sem ENV.md (instalação
398
+ // nova) ou sem os 4 eixos, o Passo 8 do /jarvis-init filtra depois.
399
+ const envOnDisk = join(ideDir, "ENV.md");
400
+ if (forceSync && existsSync(envOnDisk)) {
401
+ const { rulesSync, profileLabel } = filterRulesByEnv(cwd, ide, envOnDisk);
402
+ logRulesFilter(rulesSync, profileLabel);
403
+ if (rulesSync?.errors.length) process.exitCode = 1;
404
+ }
338
405
 
339
406
  const jarvisRoot = join(cwd, ".jarvis");
340
407
  for (const area of ["eng", "prod", "qa"]) {
@@ -502,7 +569,8 @@ async function reportCliDiscovery(entries) {
502
569
  /**
503
570
  * `jarvis init --upgrade`: atualiza um projeto já configurado em uma passada.
504
571
  * 1. arquivos do framework (como o --force, sem perguntar); 2. só as chaves novas do ENV;
505
- * 3. documentos dos caminhos antigos → docs/jarvis/… (com confirmação ou --yes).
572
+ * 3. documentos dos caminhos antigos → docs/jarvis/… (com confirmação ou --yes); 4. rules
573
+ * filtradas pelo perfil do ENV (como o `jarvis rules sync`), só com os 4 eixos preenchidos.
506
574
  * Nunca imprime valores do ENV, só nomes de chave e caminhos.
507
575
  * @returns {Promise<number>} código de saída
508
576
  */
@@ -560,7 +628,7 @@ async function runUpgrade(cwd, flags) {
560
628
  for (const item of sync.errors) logger.error(`${RED} ✗ ${item}${NC}`);
561
629
  setupMcp(workspaceDir, ide);
562
630
 
563
- // 2. Variáveis novas (só acrescenta)
631
+ // 2. Variáveis novas (acrescenta; apaga só as que saíram do template, REMOVED_KEYS)
564
632
  const envText = readFileSync(envPath, "utf-8");
565
633
  const templateText = readFileSync(
566
634
  join(getFrameworkRoot(), "templates", "ENV-template.md"),
@@ -663,6 +731,9 @@ async function runUpgrade(cwd, flags) {
663
731
  rewritten = rewriteRelatedDiscovery(workspaceDir, env, moved);
664
732
  }
665
733
 
734
+ // 3.4 Rules do perfil (#83): o mesmo filtro do `jarvis rules sync`, com o ENV.md já gravado.
735
+ const { rulesSync, missingProfile, profileLabel } = filterRulesByEnv(workspaceDir, ide, envPath);
736
+
666
737
  // 4. Resumo (só nomes de chave e caminhos)
667
738
  const pkg = getPackageInfo();
668
739
  logger.info("");
@@ -675,6 +746,12 @@ async function runUpgrade(cwd, flags) {
675
746
  logger.info(
676
747
  ` • ENV.md: ${addedKeys.length ? `+ ${addedKeys.join(", ")}` : "nenhuma variável nova"}`
677
748
  );
749
+ // Só os nomes: o valor das chaves apagadas nunca é lido (#209).
750
+ if (envPlan.removedApplied?.length) {
751
+ logger.info(
752
+ ` • ENV.md: removidas (não são mais usadas): ${envPlan.removedApplied.join(", ")}`
753
+ );
754
+ }
678
755
  if (addedKeys.includes("COMPANY_PROFILE")) {
679
756
  logger.info(
680
757
  ` • COMPANY_PROFILE: ${companyProfile ? "definido" : `default (${DEFAULT_COMPANY_PROFILE})`}`
@@ -693,6 +770,7 @@ async function runUpgrade(cwd, flags) {
693
770
  for (const e of moveErrors) logger.error(`${RED} ✗ ${e}${NC}`);
694
771
  if (staleRemoved.length) logger.info(` • Skills antigos removidos: ${staleRemoved.join(", ")}`);
695
772
  for (const e of staleErrors) logger.error(`${RED} ✗ ${e}${NC}`);
773
+ logRulesFilter(rulesSync, profileLabel);
696
774
  for (const k of envPlan.pending) {
697
775
  logger.info(`${YELLOW} ⚠️ ${k} está vazio: responda no /jarvis-init upgrade${NC}`);
698
776
  }
@@ -701,6 +779,11 @@ async function runUpgrade(cwd, flags) {
701
779
  `${YELLOW} ⚠️ Central docs no formato antigo (CENTRAL_DOCS_REPO): a migração é feita pelo /jarvis-init upgrade${NC}`
702
780
  );
703
781
  }
782
+ if (envPlan.warnings.includes("CENTRAL_DOCS_LAYOUT")) {
783
+ logger.info(
784
+ `${YELLOW} ⚠️ Central docs no layout antigo (product/engineering): rode "jarvis docs migrate" para ver o plano, ou o /jarvis-init oferece (Upgrade C)${NC}`
785
+ );
786
+ }
704
787
  if (envPlan.warnings.includes("WORKSPACE_MODE")) {
705
788
  logger.info(
706
789
  `${YELLOW} ⚠️ WORKSPACE_MODE: a raiz é um repositório e há subpastas com .git (submódulos?): gravado como project; confira no ENV.md${NC}`
@@ -727,12 +810,14 @@ async function runUpgrade(cwd, flags) {
727
810
  const access = (futureEntries.get(`${key}_ACCESS`) || "").trim();
728
811
  return getVendor(futureEntries.get(key)) && (!access || /^\[.*\]$/.test(access));
729
812
  });
730
- const pending = upgradePendencies({ pendingAxes, envPlan });
813
+ const pending = upgradePendencies({ pendingAxes, envPlan, missingProfile });
731
814
  logger.info("");
732
815
  logger.info(
733
816
  pending.length
734
817
  ? `${CYAN}➡️ Agora rode ${BOLD}/jarvis-init upgrade${NC}${CYAN} na IDE: ${pending.join("; ")}.${NC}\n`
735
818
  : `${GREEN}✓ Nada pendente na IDE.${NC}\n`
736
819
  );
737
- return sync.errors.length || moveErrors.length || staleErrors.length ? 1 : 0;
820
+ return sync.errors.length || moveErrors.length || staleErrors.length || rulesSync?.errors.length
821
+ ? 1
822
+ : 0;
738
823
  }