trackfw 3.1.0 → 5.0.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.
@@ -101,13 +101,26 @@ roadmap_namespacing: flat
101
101
  // scripts/trackfw-validate.sh
102
102
  // ---------------------------------------------------------------------------
103
103
 
104
- function generateValidateScript(cfg) {
105
- fs.mkdirSync('scripts', { recursive: true })
104
+ // generateValidateScript — cwd is optional and defaults to process.cwd() so
105
+ // existing callers (scaffold(), which always runs with process.cwd() already
106
+ // at the project root) keep working unchanged. `trackfw update`'s
107
+ // validate-script target passes cwd explicitly so this can be applied
108
+ // against a --dry-run sandbox root without ever touching the real project
109
+ // tree — this is the SAME canonical generator scaffold() uses for `init`,
110
+ // not a separate copy (see npm/src/commands/discover.js's writeValidateScript,
111
+ // which is a different, simpler generator used only by `discover`/legacy
112
+ // paths and must never be reused here — that mismatch was the ML-6H
113
+ // validate-script parity bug: init wrote the rich per-backend script,
114
+ // `update` overwrote it with the static 3-line one, so idempotent re-runs
115
+ // reported "updated" instead of "skipped").
116
+ function generateValidateScript(cfg, cwd) {
117
+ const root = cwd || process.cwd()
118
+ fs.mkdirSync(path.join(root, 'scripts'), { recursive: true })
106
119
 
107
120
  const script = buildValidateScript(cfg)
108
- const scriptPath = path.join('scripts', 'trackfw-validate.sh')
121
+ const scriptPath = path.join(root, 'scripts', 'trackfw-validate.sh')
109
122
  fs.writeFileSync(scriptPath, script, { encoding: 'utf8', mode: 0o755 })
110
- console.log(` ✓ ${scriptPath}`)
123
+ console.log(` ✓ ${path.join('scripts', 'trackfw-validate.sh')}`)
111
124
  }
112
125
 
113
126
  function buildValidateScript(cfg) {
@@ -381,14 +394,19 @@ This project uses **trackfw** for AI-native delivery governance.
381
394
  Chain: \`ADR → REQ → ROADMAP\` · States: \`backlog / analyzing / wip / blocked / done / abandoned\`
382
395
 
383
396
  ### Agent Protocol
384
- 1. **Before starting:** run \`trackfw context\` · read \`docs/agents-working-context.md\`
385
- 2. **After finishing:** update \`docs/agents-working-context.md\` with what changed
386
- 3. **Before PR:** \`trackfw validate\` must pass
387
- 4. **ML lifecycle — mandatory:**
397
+ 1. **Before any implementation (mandatory):** create governance artifacts FIRST, then branch:
398
+ \`trackfw req new "title"\` → \`trackfw roadmap new "title"\` → \`trackfw roadmap move <name> wip\` → \`git checkout -b feat/<branch>\`
399
+ ❌ Never create a branch before REQ + ROADMAP are in wip/
400
+ ❌ Never defer REQ/ROADMAP creation to a future task — they are prerequisites, not deliverables
401
+ ✓ \`trackfw validate\` enforces this via \`branch_has_wip_roadmap\` rule (v2.7.0+)
402
+ 2. **Before starting:** run \`trackfw context\` · read \`docs/agents-working-context.md\`
403
+ 3. **After finishing:** update \`docs/agents-working-context.md\` with what changed
404
+ 4. **Before PR:** \`trackfw validate\` must pass
405
+ 5. **ML lifecycle — mandatory:**
388
406
  - Starting a ML: edit roadmap \`**Status:** ⬜ Pendente\` → \`**Status:** 🔄 Em andamento\` + commit.
389
407
  - Completing a ML: edit roadmap → \`**Status:** ✅ Concluído\` + include in ML commit.
390
408
  - Analyzing a roadmap: move from \`backlog/\` to \`analyzing/\`; to \`wip/\` only when coding starts.
391
- 5. **${GLOBAL_ADRS_DIRECTIVE}**
409
+ 6. **${GLOBAL_ADRS_DIRECTIVE}**
392
410
 
393
411
  ### Attention Signal (when you need user input during a task)
394
412
  Write \`docs/roadmaps/.trackfw-attention.json\`:
@@ -411,6 +429,13 @@ Delete the file when resolved. Visible as a live banner in \`trackfw serve\`.
411
429
  - **Security wave:** include a red-team review wave in every feature roadmap
412
430
  - **Test coverage:** TDD for critical logic; min 60% (prototype) / 80% (production)
413
431
  - Use \`/trackfw:architect\` to define stack before the first REQ
432
+
433
+ ### Key Commands
434
+ - \`trackfw context\` — current governance state (always run first)
435
+ - \`trackfw status\` — all artifacts and states
436
+ - \`trackfw validate\` — governance consistency check
437
+ - \`trackfw roadmap move <name> <state>\` — transition roadmap state
438
+ - \`trackfw serve\` — live Kanban board at http://localhost:4080
414
439
  ` + RULES_END
415
440
  }
416
441
 
@@ -529,7 +554,8 @@ function generateClaudeMD(cfg) {
529
554
  content += '| `/trackfw:roadmap <req>` | Generate AI roadmap from a REQ |\n'
530
555
  content += '| `/trackfw:move <name> <state>` | Move roadmap between states manually |\n'
531
556
  content += '| `/trackfw:validate` | Run governance validation |\n'
532
- content += '| `/trackfw:status` | Check what is in flight |\n\n'
557
+ content += '| `/trackfw:status` | Check what is in flight |\n'
558
+ content += '| `/trackfw:barrier` | Run the wave-release checklist before liberating the next wave |\n\n'
533
559
 
534
560
  content += '## CLI commands (terminal / CI)\n\n'
535
561
  content += '| Command | When to use |\n'
@@ -698,14 +724,20 @@ function backendCommands(cfg) {
698
724
  }
699
725
 
700
726
  // ---------------------------------------------------------------------------
701
- // .claude/commands/trackfw/ — 7 slash commands
727
+ // .claude/commands/trackfw/ — slash commands
728
+ //
729
+ // CLAUDE_COMMANDS is the single source of truth for the set of slash
730
+ // commands installed by trackfw. Both generateClaudeCommands (normal path,
731
+ // idempotent — never overwrites an existing file) and
732
+ // generateClaudeCommandsForce (force path — always overwrites) install
733
+ // from this same map; they only differ in overwrite behavior. This mirrors
734
+ // the Go CLI's installSkillsInner(force) and the Python CLI's single
735
+ // generate_claude_commands — one list, one force flag. Do not fork this map
736
+ // again: a prior divergence let the force path fall behind the normal path
737
+ // (missing roadmap.md, implement.md, barrier.md) undetected.
702
738
  // ---------------------------------------------------------------------------
703
739
 
704
- function generateClaudeCommands() {
705
- const dir = '.claude/commands/trackfw'
706
- fs.mkdirSync(dir, { recursive: true })
707
-
708
- const commands = {
740
+ const CLAUDE_COMMANDS = {
709
741
  'adr.md': `Execute o seguinte comando bash: \`trackfw adr new "$ARGUMENTS"\`
710
742
 
711
743
  Se o comando falhar com \`trackfw: command not found\` ou similar, informe ao usuário:
@@ -949,6 +981,51 @@ Roadmap: docs/roadmaps/done/<nome>.md
949
981
  Próximo passo: abrir PR com gh pr create
950
982
  \`\`\``,
951
983
 
984
+ 'barrier.md': `Você é o \`trackfw_architect\`, a única autoridade Git deste projeto. Este comando executa o checklist operacional de liberação de uma wave — nenhum outro agente commita, faz push ou libera a próxima wave.
985
+
986
+ ## Argumento
987
+
988
+ \`$ARGUMENTS\` no formato \`<roadmap> <wave>\`. Se ausente ou incompleto, pergunte ao usuário qual roadmap (em \`docs/roadmaps/wip/\`) e qual número de wave validar.
989
+
990
+ ---
991
+
992
+ ## Núcleo determinístico
993
+
994
+ Execute primeiro:
995
+ \`\`\`bash
996
+ trackfw barrier <roadmap> --wave <n> --json
997
+ \`\`\`
998
+
999
+ Este comando é **necessário mas não suficiente**. Ele verifica MLs concluídos, evidências e \`trackfw validate\`, mas não substitui as inspeções especializadas nem a auditoria de diff abaixo — nenhuma delas é avaliada pelo binário. Consulte a seção \`trackfw barrier\` em \`docs/cli-parity.md\` para o contrato completo (estados, exit codes, saída JSON).
1000
+
1001
+ Se o comando retornar exit code não-zero (\`blocked\` ou erro de resolução): pare, reporte a falha ao usuário e não prossiga no checklist até que a wave passe.
1002
+
1003
+ ---
1004
+
1005
+ ## Definição de pronto da barrier — checklist completo
1006
+
1007
+ Antes de liberar a próxima wave, confirme cada item com evidência concreta — não presuma:
1008
+
1009
+ 1. **Todos os MLs da wave concluídos e marcados** — cada ML da wave está com \`**Status:** ✅ Concluído\` no roadmap.
1010
+ 2. **Testes unitários e E2E aplicáveis executados** — rode os comandos de validação declarados em cada ML.
1011
+ 3. **Build aplicável sem erros** — rode o comando de build do(s) workspace(s) afetado(s).
1012
+ 4. **Cada critério de aceite inspecionado com evidência** — leia os arquivos modificados e confirme contra os critérios listados, não apenas contra os testes.
1013
+ 5. **Agente code-quality reportou conformidade, performance, robustez e clareza** — invoque o agente \`code-quality\` quando a mudança introduzir lógica nova, duplicação relevante ou risco de manutenibilidade.
1014
+ 6. **Agente security reportou SAST, privilégios, controle de acesso e camadas aplicáveis** — invoque o agente \`security\` quando a mudança tocar autenticação, segredos, entrada externa ou permissões.
1015
+ 7. **Gates pré-commit declarados pelo projeto executados** — rode os hooks/gates configurados (lint, format, testes de contrato).
1016
+ 8. **\`trackfw validate --json\` aprovado** — execute e confirme zero violações.
1017
+ 9. **Diff auditado contra o escopo** — revise o diff completo; confirme que não há alterações de agentes concorrentes nem arquivos fora do escopo do ML (ex: \`docs/adr/\`, \`docs/req/\`, \`docs/roadmaps/\` quando não autorizado ao especialista).
1018
+ 10. **Resultado registrado antes de liberar a próxima wave** — anote no roadmap ou na resposta ao usuário que a wave passou, com a evidência de cada item acima.
1019
+
1020
+ Se qualquer item falhar: bloqueie a próxima wave, identifique o item e o agente responsável, e despache um microlote corretivo. Só repita o checklist depois que o corretivo for concluído.
1021
+
1022
+ ---
1023
+
1024
+ ## Autoridade Git
1025
+
1026
+ Somente o \`trackfw_architect\` cria branch, audita diff, commita e faz push. Especialistas entregam trabalho sem commit — cabe a este papel revisar, commitar e sugerir a abertura de PR/MR (sem abrir automaticamente sem autorização do usuário).
1027
+ `,
1028
+
952
1029
  'architect.md': `Você é o guia de arquitetura do trackfw. Ajude o usuário a escolher a stack correta e arquitetar a aplicação em linguagem simples, acessível para times não técnicos.
953
1030
 
954
1031
  ## Passo 1 — Descoberta de Negócio
@@ -1027,13 +1104,21 @@ Oriente o usuário:
1027
1104
  2. Gere o roadmap em microlotes com /trackfw:roadmap
1028
1105
  3. Inicie a implementação com /trackfw:implement
1029
1106
  \`\`\``,
1030
- }
1107
+ }
1108
+
1109
+ /**
1110
+ * installClaudeCommandsInner — fonte única de escrita dos slash commands.
1111
+ * @param {string} dir diretório de destino (já resolvido)
1112
+ * @param {boolean} force quando true, sobrescreve arquivos existentes
1113
+ */
1114
+ function installClaudeCommandsInner(dir, force) {
1115
+ fs.mkdirSync(dir, { recursive: true })
1031
1116
 
1032
1117
  let created = 0
1033
1118
  let skipped = 0
1034
- for (const [filename, content] of Object.entries(commands)) {
1119
+ for (const [filename, content] of Object.entries(CLAUDE_COMMANDS)) {
1035
1120
  const filePath = path.join(dir, filename)
1036
- if (fs.existsSync(filePath)) {
1121
+ if (!force && fs.existsSync(filePath)) {
1037
1122
  skipped++
1038
1123
  continue
1039
1124
  }
@@ -1041,13 +1126,28 @@ Oriente o usuário:
1041
1126
  created++
1042
1127
  }
1043
1128
 
1044
- if (skipped > 0) {
1129
+ if (force) {
1130
+ console.log(` ✓ ${dir} (${created} slash commands sobrescritos)`)
1131
+ } else if (skipped > 0) {
1045
1132
  console.log(` ✓ ${dir} (${created} slash commands criados, ${skipped} já existiam — não sobrescritos)`)
1046
1133
  } else {
1047
1134
  console.log(` ✓ ${dir} (${created} slash commands)`)
1048
1135
  }
1049
1136
  }
1050
1137
 
1138
+ /**
1139
+ * generateClaudeCommands — instala os slash commands de forma idempotente:
1140
+ * nunca sobrescreve um arquivo já existente. Honra o `rootDir` recebido
1141
+ * (mesma convenção do gêmeo forçado generateClaudeCommandsForce e do
1142
+ * generate_claude_commands(cwd) do Python); quando omitido, cai no
1143
+ * caminho relativo ao cwd do processo, preservando o comportamento
1144
+ * histórico consumido pelos testes que chamam sem argumento.
1145
+ */
1146
+ function generateClaudeCommands(rootDir) {
1147
+ const dir = rootDir ? path.join(rootDir, '.claude', 'commands', 'trackfw') : '.claude/commands/trackfw'
1148
+ installClaudeCommandsInner(dir, false)
1149
+ }
1150
+
1051
1151
  // ---------------------------------------------------------------------------
1052
1152
  // AI tool installers
1053
1153
  // ---------------------------------------------------------------------------
@@ -1117,10 +1217,10 @@ async function installAmazonQ(cwd = process.cwd()) {
1117
1217
  * resolved (ADR-2026-07-25-escopo-de-instalacao-selecionavel-para-agents-e-
1118
1218
  * skills, D4).
1119
1219
  */
1120
- async function installIntegrationTarget(target, cwd = process.cwd(), scope = 'project') {
1220
+ async function installIntegrationTarget(target, cwd = process.cwd(), scope = 'project', { onSkip } = {}) {
1121
1221
  const { execute, buildPlans } = require('../integrations')
1122
1222
  const roots = { projectRoot: cwd }
1123
- const options = { targets: [target], scope }
1223
+ const options = { targets: [target], scope, onSkip }
1124
1224
  // D5 — transparency: print resolved destinations before writing anything.
1125
1225
  // buildPlans has no side effects, so it is safe to call here purely to
1126
1226
  // enumerate destinations; the actual write happens below via execute().
@@ -1140,25 +1240,13 @@ async function installIntegrationTarget(target, cwd = process.cwd(), scope = 'pr
1140
1240
  }
1141
1241
 
1142
1242
  /**
1143
- * generateClaudeCommandsForce — re-gera todos os slash commands, sobrescrevendo arquivos existentes.
1243
+ * generateClaudeCommandsForce — re-gera todos os slash commands, sobrescrevendo
1244
+ * arquivos existentes. Instala exatamente o mesmo conjunto de CLAUDE_COMMANDS
1245
+ * usado por generateClaudeCommands — só o comportamento de sobrescrita difere.
1144
1246
  */
1145
1247
  function generateClaudeCommandsForce(rootDir) {
1146
1248
  const dir = rootDir ? path.join(rootDir, '.claude', 'commands', 'trackfw') : '.claude/commands/trackfw'
1147
- fs.mkdirSync(dir, { recursive: true })
1148
-
1149
- const commands = {
1150
- 'adr.md': `Execute o seguinte comando bash: \`trackfw adr new "$ARGUMENTS"\`\n\nSe o comando falhar com \`trackfw: command not found\` ou similar, informe ao usuário:\n\n\`\`\`\ntrackfw não está instalado. Instale com uma das opções:\n\n curl -sSfL https://github.com/kgsaran/trackfw/releases/latest/download/install.sh | sh\n npm install -g trackfw\n pip install trackfw\n\`\`\``,
1151
- 'req.md': `Execute o seguinte comando bash: \`trackfw req new "$ARGUMENTS"\`\n\nSe o comando falhar com \`trackfw: command not found\` ou similar, informe ao usuário:\n\n\`\`\`\ntrackfw não está instalado. Instale com uma das opções:\n\n curl -sSfL https://github.com/kgsaran/trackfw/releases/latest/download/install.sh | sh\n npm install -g trackfw\n pip install trackfw\n\`\`\``,
1152
- 'validate.md': `Execute o seguinte comando bash: \`trackfw validate\`\n\nSe o comando falhar com \`trackfw: command not found\` ou similar, informe ao usuário:\n\n\`\`\`\ntrackfw não está instalado. Instale com uma das opções:\n\n curl -sSfL https://github.com/kgsaran/trackfw/releases/latest/download/install.sh | sh\n npm install -g trackfw\n pip install trackfw\n\`\`\``,
1153
- 'status.md': `Execute o seguinte comando bash: \`trackfw status\`\n\nSe o comando falhar com \`trackfw: command not found\` ou similar, informe ao usuário:\n\n\`\`\`\ntrackfw não está instalado. Instale com uma das opções:\n\n curl -sSfL https://github.com/kgsaran/trackfw/releases/latest/download/install.sh | sh\n npm install -g trackfw\n pip install trackfw\n\`\`\``,
1154
- 'move.md': `Execute o seguinte comando bash: \`trackfw roadmap move $ARGUMENTS\`\n\nO formato esperado é: \`<nome-do-roadmap> <estado>\`\nEstados válidos: \`backlog\`, \`analyzing\`, \`wip\`, \`blocked\`, \`done\`, \`abandoned\`\n\nSe o comando falhar, instale trackfw com:\n curl -sSfL https://github.com/kgsaran/trackfw/releases/latest/download/install.sh | sh`,
1155
- 'architect.md': `Você é o guia de arquitetura do trackfw. Ajude o usuário a escolher a stack correta e arquitetar a aplicação em linguagem simples, acessível para times não técnicos.\n\n## Passo 1 — Descoberta de Negócio\n\nFaça ao usuário as seguintes perguntas em linguagem simples, uma por vez:\n\n1. "O que sua aplicação vai fazer? Descreva em 2-3 frases como se fosse explicar para alguém de fora da TI."\n2. "Quantas pessoas vão usar esse sistema simultaneamente? (< 10 pessoas / 10-100 pessoas / > 100 pessoas)"\n3. "Esse sistema vai para produção de verdade ou é um protótipo para validar uma ideia?"\n4. "Você precisa de login/autenticação de usuários? (Sim / Não / Não sei)"\n5. "Tem alguma restrição de tecnologia ou preferência da empresa? (ex: só Java, só Microsoft, etc.)"\n\n---\n\n## Passo 2 — Recomendação de Stack\n\nCom base nas respostas, escolha **UM** dos combos pré-validados:\n\n### Combo A — Protótipo Rápido\n**Quando usar:** prototipagem, validação de ideia, até ~10 usuários, sem pressão de produção.\n- **Frontend:** React + Vite\n- **Backend:** FastAPI (Python) ou Express (Node.js)\n- **Banco:** SQLite + SQLAlchemy / Prisma\n- **Auth:** JWT simples quando necessário\n- **Docker:** Dockerfile básico para o backend\n\n### Combo B — Sistema Pequeno/Médio em Produção\n**Quando usar:** sistema real, 10-100 usuários, robustez e manutenibilidade.\n- **Frontend:** Next.js (SSR + rotas prontas)\n- **Backend:** FastAPI (Python) ou NestJS (Node.js)\n- **Banco:** PostgreSQL + ORM (SQLAlchemy / Prisma / TypeORM)\n- **Auth:** OAuth2 com JWT (Supabase Auth ou Auth0)\n- **Docker:** docker-compose com frontend + backend + banco\n\n### Combo C — Enterprise / Java\n**Quando usar:** integração com sistemas corporativos, > 100 usuários, exigência de Java.\n- **Frontend:** Angular\n- **Backend:** Spring Boot\n- **Banco:** PostgreSQL + Hibernate\n- **Auth:** Spring Security + OAuth2 (Keycloak ou Azure AD)\n- **Docker:** docker-compose com todos os serviços\n\nApresente o combo recomendado com explicação simples do motivo.\n\n---\n\n## Passo 3 — Arquitetura em Camadas (explicação simples)\n\nExplique a arquitetura com uma metáfora de negócio:\n\n"Pense na aplicação como um restaurante:\n- **Frontend** = o salão: o que o cliente vê e interage\n- **Backend** = a cozinha: onde as regras de negócio acontecem, nunca exposta diretamente\n- **Banco de dados** = a despensa: onde os dados ficam guardados, acessada só pela cozinha"\n\nReforce as **Architecture Directives** já injetadas no CLAUDE.md deste projeto: separação em 3 camadas sem dados em memória (sempre DB + ORM), auth + Docker + .env desde o dia 1, validação em 2 camadas, contrato OpenAPI antes de codar, wave de segurança em todo roadmap e cobertura mínima de testes (60% protótipo / 80% produção).\n\n---\n\n## Passo 4 — Gerar o ADR de Stack\n\nExecute \`/trackfw:adr\` com o título: \`"Stack e arquitetura em camadas — [nome do projeto]"\`\n\nO ADR deve registrar a stack escolhida (combo e componentes), motivação baseada nas respostas, alternativas descartadas e princípios de arquitetura adotados.\n\n---\n\n## Passo 5 — Próximos Passos\n\nOriente o usuário:\n\n\`\`\`\n✅ Stack definida. Próximos passos:\n\n1. Crie a REQ da primeira feature com /trackfw:req\n2. Gere o roadmap em microlotes com /trackfw:roadmap\n3. Inicie a implementação com /trackfw:implement\n\`\`\``,
1156
- }
1157
-
1158
- for (const [filename, content] of Object.entries(commands)) {
1159
- fs.writeFileSync(path.join(dir, filename), content, 'utf8')
1160
- }
1161
- console.log(` ✓ .claude/commands/trackfw/ (${Object.keys(commands).length} slash commands sobrescritos)`)
1249
+ installClaudeCommandsInner(dir, true)
1162
1250
  }
1163
1251
 
1164
1252
  /**
@@ -3,6 +3,7 @@ const fs = require('fs')
3
3
  const path = require('path')
4
4
  const config = require('../config')
5
5
  const { localDateISO } = require('./date')
6
+ const { resolveReqFiles } = require('../validator/index.js')
6
7
 
7
8
  const VALID_STATES = ['backlog', 'analyzing', 'wip', 'blocked', 'done', 'abandoned']
8
9
  const STATE_ORDER = ['analyzing', 'wip', 'backlog', 'blocked', 'done', 'abandoned']
@@ -251,6 +252,9 @@ function moveRoadmap(name, state) {
251
252
 
252
253
  appendTransitionLog(logBasename, fromState, state)
253
254
  console.log(`✓ moved ${basename} → ${targetDir}`)
255
+
256
+ // Sincroniza o roadmap: das REQs que apontem para este roadmap.
257
+ syncReqReferences(basename, dst, cfg)
254
258
  }
255
259
 
256
260
  /**
@@ -273,6 +277,124 @@ function appendTransitionLog(basename, fromState, toState) {
273
277
  } catch (_) {}
274
278
  }
275
279
 
280
+ /**
281
+ * extractFrontmatterRoadmap — extrai o valor do campo `roadmap:` SOMENTE do frontmatter.
282
+ * Retorna null se não encontrado ou se não termina em .md.
283
+ * Não usa extractRefPath do validator porque este percorre todo o conteúdo (inclusive corpo)
284
+ * sem distinguir frontmatter de body — geraria falsos positivos em REQs sem roadmap: no FM.
285
+ */
286
+ function extractFrontmatterRoadmap(content) {
287
+ const lines = content.split('\n')
288
+ let inFm = false
289
+ for (let i = 0; i < lines.length; i++) {
290
+ const line = lines[i]
291
+ if (i === 0 && line.trim() === '---') { inFm = true; continue }
292
+ if (inFm && line.trim() === '---') return null // fechou frontmatter sem encontrar
293
+ if (!inFm) return null // nunca entrou no frontmatter
294
+ const idx = line.indexOf(':')
295
+ if (idx === -1) continue
296
+ if (line.slice(0, idx).trim() !== 'roadmap') continue
297
+ let val = line.slice(idx + 1).trim()
298
+ val = val.replace(/^["']|["']$/g, '').trim()
299
+ if (val.endsWith('.md')) return val
300
+ return null // roadmap: existe mas sem .md (ex: "" ou slug)
301
+ }
302
+ return null
303
+ }
304
+
305
+ /**
306
+ * rewriteReqRoadmapRef — reescreve o campo `roadmap:` no frontmatter e a linha `Roadmap:` no
307
+ * corpo de uma REQ, substituindo oldRef por newRef.
308
+ * Preserva toda formatação existente (aspas, backticks) via substituição literal de string.
309
+ */
310
+ function rewriteReqRoadmapRef(content, oldRef, newRef) {
311
+ const lines = content.split('\n')
312
+ let inFm = false
313
+ let fmDone = false
314
+ const result = []
315
+
316
+ for (let i = 0; i < lines.length; i++) {
317
+ const line = lines[i]
318
+ if (i === 0 && line.trim() === '---') { inFm = true; result.push(line); continue }
319
+ if (inFm && line.trim() === '---') { inFm = false; fmDone = true; result.push(line); continue }
320
+ if (inFm) {
321
+ const idx = line.indexOf(':')
322
+ if (idx !== -1 && line.slice(0, idx).trim() === 'roadmap' && line.includes(oldRef)) {
323
+ result.push(line.replace(oldRef, newRef))
324
+ continue
325
+ }
326
+ result.push(line)
327
+ continue
328
+ }
329
+ if (fmDone) {
330
+ // No corpo: reescreve linhas `Roadmap:` que contenham oldRef
331
+ if (line.trim().toLowerCase().startsWith('roadmap:') && line.includes(oldRef)) {
332
+ result.push(line.replace(oldRef, newRef))
333
+ continue
334
+ }
335
+ }
336
+ result.push(line)
337
+ }
338
+
339
+ return result.join('\n')
340
+ }
341
+
342
+ /**
343
+ * syncReqReferences — após rename bem-sucedido, varre req_dir (flat + by_agent) e reescreve o
344
+ * frontmatter `roadmap:` e a linha `Roadmap:` do corpo em toda REQ que aponte para o roadmap
345
+ * movido. Implementa as cinco cardinalidades do contrato:
346
+ * zero → no-op silencioso; uma → reescreve; várias → reescreve todas; aponta para outro →
347
+ * não toca; já correta → nenhuma escrita (idempotente byte-a-byte).
348
+ * Erros: diagnóstico em stderr nomeando a REQ; tenta as restantes; exit não-zero ao fim.
349
+ */
350
+ function syncReqReferences(movedBasename, newRoadmapPath, cfg) {
351
+ // Ordenação explícita por basename (independente de locale) para garantir saída determinística
352
+ // independente do filesystem. Desempate por caminho completo quando dois agentes têm REQs de
353
+ // mesmo basename. Não confiar na ordem do readdirSync — varia entre filesystems.
354
+ const files = resolveReqFiles(cfg).sort((a, b) => {
355
+ const ba = path.basename(a)
356
+ const bb = path.basename(b)
357
+ if (ba < bb) return -1
358
+ if (ba > bb) return 1
359
+ if (a < b) return -1
360
+ if (a > b) return 1
361
+ return 0
362
+ })
363
+ let anyError = false
364
+
365
+ for (const filePath of files) {
366
+ let content
367
+ try {
368
+ content = fs.readFileSync(filePath, 'utf8')
369
+ } catch (e) {
370
+ console.error(`trackfw roadmap move: failed to sync ${path.basename(filePath)}: ${e.message}`)
371
+ anyError = true
372
+ continue
373
+ }
374
+
375
+ const currentRef = extractFrontmatterRoadmap(content)
376
+ if (!currentRef) continue
377
+ if (path.basename(currentRef) !== movedBasename) continue // aponta para outro roadmap
378
+ if (currentRef === newRoadmapPath) {
379
+ // Guarda rápida: frontmatter já correto — confirma idempotência com reescrita estrutural
380
+ const updated = rewriteReqRoadmapRef(content, currentRef, newRoadmapPath)
381
+ if (updated === content) continue // sem escrita, sem output
382
+ }
383
+
384
+ try {
385
+ const updated = rewriteReqRoadmapRef(content, currentRef, newRoadmapPath)
386
+ if (updated === content) continue // nenhuma escrita, nenhum output (idempotência byte-a-byte)
387
+ fs.writeFileSync(filePath, updated, 'utf8')
388
+ console.log(`✓ synced ${path.basename(filePath)} → ${newRoadmapPath}`)
389
+ } catch (e) {
390
+ console.error(`trackfw roadmap move: failed to sync ${path.basename(filePath)}: ${e.message}`)
391
+ anyError = true
392
+ }
393
+ }
394
+
395
+ if (anyError) process.exitCode = 1
396
+ }
397
+
276
398
  /**
277
399
  * newRoadmap — cria roadmap em <roadmapDir>/backlog/ROADMAP-YYYY-MM-DD-<slug>.md.
278
400
  * Em modo by_agent, usa o primeiro agente configurado.
@@ -524,6 +646,9 @@ module.exports = {
524
646
  moveRoadmap,
525
647
  rewriteRoadmapStatus,
526
648
  appendTransitionLog,
649
+ extractFrontmatterRoadmap,
650
+ rewriteReqRoadmapRef,
651
+ syncReqReferences,
527
652
  newRoadmap,
528
653
  newRoadmapFromReq,
529
654
  stateDir,
@@ -24,7 +24,10 @@ Append an entry to `docs/agents-working-context.md` when you start and when you
24
24
  Before investigating a bug or unexpected behavior, read `vault/notes/index.md` when it exists and open the related notes. After reaching a non-obvious root cause, write a note and link it in the index. Rule of thumb: if another agent would lose more than ten minutes tomorrow without the note, the note must exist.
25
25
 
26
26
  ## Git authority
27
- This is the only role allowed to create branches (`git checkout -b`). Commits from this role are limited to orchestration artifacts: ADRs, REQs, roadmaps, vault notes and the working context file. Never commit product code. Push to the working branch, and open a pull request only when the user explicitly asks. Never merge.
27
+ `trackfw_architect` is the **only** role with Git authority in this project. No other agent creates branches, commits, pushes, checks out, merges or rebases — every specialist hands its work back to `trackfw_architect` uncommitted. This role: creates the branch (`git checkout -b`) before any handoff; audits the full diff produced by specialists against the assigned scope; performs every commit, including orchestration artifacts (ADRs, REQs, roadmaps, vault notes, the working context file) and the product code produced by specialists once audited; pushes to the working branch; and suggests opening a pull request, opening it only when the user explicitly asks. Never merge.
28
+
29
+ ## Barrier protocol
30
+ Before releasing the next wave: invoke the `code-quality` and `security` roles whenever the change warrants their review (new code paths, dependencies, permissions, secrets, parsers, or attack surface); block the next wave on any failed check and dispatch a corrective microbatch to the owning role instead of proceeding; audit the diff and re-run the wave's gates before performing any commit. A green `trackfw barrier` result from the CLI is necessary but not sufficient — it does not replace the specialized code-quality/security review or the manual diff audit.
28
31
 
29
32
  ## Parallelization
30
33
  Analyze real dependencies between microbatches before assigning work. Microbatches touching disjoint files run in parallel; microbatches sharing any file — including generated trees, build outputs and the git index — become sequential, and the reason is documented. Put an explicit barrier between waves. Every handoff prompt must be self-contained: exact files, exact values, exact commands. Never let two agents edit the same file at the same time.
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -29,6 +29,9 @@ Do not edit code without a requirement and a roadmap already in the `wip` state.
29
29
  ## Reporting boundary
30
30
  You do not modify code. Report findings ordered by severity, each with concrete evidence (file, line, and the observed behavior), and hand off the fix to the role that owns the code. Never weaken a control, a test or a permission to make something pass.
31
31
 
32
+ ## Git authority
33
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
34
+
32
35
  ## Definition of done
33
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
34
37
 
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -28,11 +28,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
28
28
  ## Governance prerequisite
29
29
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
30
30
 
31
- ## Git boundary
32
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
31
+ ## Git authority
32
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
33
33
 
34
34
  ## Microbatch completion protocol
35
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
35
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
36
36
 
37
37
  ## Definition of done
38
38
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -28,11 +28,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
28
28
  ## Governance prerequisite
29
29
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
30
30
 
31
- ## Git boundary
32
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
31
+ ## Git authority
32
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
33
33
 
34
34
  ## Microbatch completion protocol
35
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
35
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
36
36
 
37
37
  ## Definition of done
38
38
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -29,6 +29,9 @@ Do not edit code without a requirement and a roadmap already in the `wip` state.
29
29
  ## Reporting boundary
30
30
  You do not modify code. Report findings ordered by severity, each with concrete evidence (file, line, and the observed behavior), and hand off the fix to the role that owns the code. Never weaken a control, a test or a permission to make something pass.
31
31
 
32
+ ## Git authority
33
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
34
+
32
35
  ## Definition of done
33
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
34
37
 
@@ -26,11 +26,11 @@ Before investigating a bug or unexpected behavior, read `vault/notes/index.md` w
26
26
  ## Governance prerequisite
27
27
  Do not edit code without a requirement and a roadmap already in the `wip` state. Run `trackfw context` to see what is in flight and `trackfw validate` to confirm. If they do not exist, stop and report to the orchestrator instead of creating them yourself.
28
28
 
29
- ## Git boundary
30
- You must not create branches and must not open pull requests. Commit only on the branch the orchestrator already created, using Conventional Commits, with no agent name suffix and no AI model trailer.
29
+ ## Git authority
30
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
31
31
 
32
32
  ## Microbatch completion protocol
33
- In order: build, tests, project gate, `trackfw validate`, commit, push, then update the microbatch status in the roadmap. Report the exact command output as evidence, not a summary of it.
33
+ In order: build, tests, project gate, `trackfw validate`, then report the exact command output as evidence and hand the microbatch back to `trackfw_architect` for audit and commit. Update the microbatch status in the roadmap only after the orchestrator's audit passes.
34
34
 
35
35
  ## Definition of done
36
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
@@ -29,6 +29,9 @@ Do not edit code without a requirement and a roadmap already in the `wip` state.
29
29
  ## Reporting boundary
30
30
  You do not modify code. Report findings ordered by severity, each with concrete evidence (file, line, and the observed behavior), and hand off the fix to the role that owns the code. Never weaken a control, a test or a permission to make something pass.
31
31
 
32
+ ## Git authority
33
+ This role never executes Git operations — no `branch`, `commit`, `push`, `checkout`, `merge`, `rebase` or `stash`. `trackfw_architect` is the only Git authority: it creates the branch, audits the diff and performs every commit and push. Act only on a self-contained handoff from `trackfw_architect`; refuse to implement anything without one.
34
+
32
35
  ## Definition of done
33
36
  Green build and tests do not close a microbatch. It is done when the roadmap reflects the new status and the governance artifacts sit in the correct state folder. Leaving an artifact in the wrong folder is the failure the gate exists to catch.
34
37