atlas-workflow 0.9.0 → 0.9.2

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 (111) hide show
  1. package/README.md +2 -2
  2. package/VERSION +1 -1
  3. package/build/cli/atlas-init.mjs +12 -14
  4. package/build/tests/classify-findings.test.mjs +20 -0
  5. package/build/tests/etapa3.test.mjs +161 -0
  6. package/build/tests/test_classify_findings.py +79 -0
  7. package/hosts/opencode/.opencode/agents/atlas-findings-repair.md +4 -0
  8. package/hosts/opencode/.opencode/agents/atlas-task-validator.md +18 -1
  9. package/hosts/opencode/.opencode/atlas/VERSION +1 -1
  10. package/hosts/opencode/.opencode/atlas/orchestrator/README.md +7 -5
  11. package/hosts/opencode/.opencode/atlas/orchestrator/commands/workflow.md +1 -1
  12. package/hosts/opencode/.opencode/atlas/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  13. package/hosts/opencode/.opencode/atlas/packages/mcp-server/README.md +1 -1
  14. package/hosts/opencode/.opencode/atlas/packages/mcp-server/package.json +1 -1
  15. package/hosts/opencode/.opencode/atlas/packages/mcp-server/server.js +446 -14
  16. package/hosts/opencode/.opencode/atlas/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  17. package/hosts/opencode/.opencode/atlas/packages/templates/PRD_TEMPLATE.md +2 -1
  18. package/hosts/opencode/.opencode/atlas/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  19. package/hosts/opencode/.opencode/skills/_shared/references/stack-profiles.md +36 -0
  20. package/hosts/opencode/.opencode/skills/_shared/scripts/document_quality.mjs +252 -0
  21. package/hosts/opencode/.opencode/skills/atlas-backlog-generator/SKILL.md +7 -2
  22. package/hosts/opencode/.opencode/skills/atlas-direct-execute/SKILL.md +6 -2
  23. package/hosts/opencode/.opencode/skills/atlas-findings-repair/SKILL.md +11 -1
  24. package/hosts/opencode/.opencode/skills/atlas-plan-execute/SKILL.md +16 -2
  25. package/hosts/opencode/.opencode/skills/atlas-plan-handoff/SKILL.md +6 -4
  26. package/hosts/opencode/.opencode/skills/atlas-prd-interview/SKILL.md +7 -2
  27. package/hosts/opencode/.opencode/skills/atlas-slice-review/SKILL.md +37 -2
  28. package/hosts/opencode/.opencode/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  29. package/hosts/opencode/.opencode/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  30. package/hosts/opencode/.opencode/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  31. package/hosts/opencode/.opencode/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  32. package/hosts/opencode/.opencode/skills/atlas-task-validator/SKILL.md +29 -14
  33. package/hosts/opencode/.opencode/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  34. package/hosts/pi/.pi/agents/atlas-direct-execute.md +6 -2
  35. package/hosts/pi/.pi/agents/atlas-findings-repair.md +15 -1
  36. package/hosts/pi/.pi/agents/atlas-plan-execute.md +16 -2
  37. package/hosts/pi/.pi/agents/atlas-slice-review.md +37 -2
  38. package/hosts/pi/.pi/agents/atlas-task-validator.md +18 -1
  39. package/hosts/pi/atlas/VERSION +1 -1
  40. package/hosts/pi/atlas/orchestrator/README.md +7 -5
  41. package/hosts/pi/atlas/orchestrator/commands/workflow.md +1 -1
  42. package/hosts/pi/atlas/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  43. package/hosts/pi/atlas/packages/mcp-server/README.md +1 -1
  44. package/hosts/pi/atlas/packages/mcp-server/package.json +1 -1
  45. package/hosts/pi/atlas/packages/mcp-server/server.js +446 -14
  46. package/hosts/pi/atlas/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  47. package/hosts/pi/atlas/packages/templates/PRD_TEMPLATE.md +2 -1
  48. package/hosts/pi/atlas/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  49. package/hosts/pi/skills/_shared/references/stack-profiles.md +36 -0
  50. package/hosts/pi/skills/_shared/scripts/document_quality.mjs +252 -0
  51. package/hosts/pi/skills/atlas-backlog-generator/SKILL.md +7 -2
  52. package/hosts/pi/skills/atlas-direct-execute/SKILL.md +6 -2
  53. package/hosts/pi/skills/atlas-findings-repair/SKILL.md +11 -1
  54. package/hosts/pi/skills/atlas-plan-execute/SKILL.md +16 -2
  55. package/hosts/pi/skills/atlas-plan-handoff/SKILL.md +6 -4
  56. package/hosts/pi/skills/atlas-prd-interview/SKILL.md +7 -2
  57. package/hosts/pi/skills/atlas-slice-review/SKILL.md +37 -2
  58. package/hosts/pi/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  59. package/hosts/pi/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  60. package/hosts/pi/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  61. package/hosts/pi/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  62. package/hosts/pi/skills/atlas-task-validator/SKILL.md +29 -14
  63. package/hosts/pi/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  64. package/package.json +1 -1
  65. package/plugins/atlas-workflow-orchestrator/.codex/agents/atlas-findings-repair.toml +1 -1
  66. package/plugins/atlas-workflow-orchestrator/.codex/agents/atlas-task-validator.toml +1 -1
  67. package/plugins/atlas-workflow-orchestrator/.codex-plugin/plugin.json +1 -1
  68. package/plugins/atlas-workflow-orchestrator/VERSION +1 -1
  69. package/plugins/atlas-workflow-orchestrator/agents/atlas-findings-repair.md +4 -0
  70. package/plugins/atlas-workflow-orchestrator/agents/atlas-task-validator.md +18 -1
  71. package/plugins/atlas-workflow-orchestrator/orchestrator/README.md +7 -5
  72. package/plugins/atlas-workflow-orchestrator/orchestrator/commands/workflow.md +1 -1
  73. package/plugins/atlas-workflow-orchestrator/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  74. package/plugins/atlas-workflow-orchestrator/packages/mcp-server/README.md +1 -1
  75. package/plugins/atlas-workflow-orchestrator/packages/mcp-server/package.json +1 -1
  76. package/plugins/atlas-workflow-orchestrator/packages/mcp-server/server.js +446 -14
  77. package/plugins/atlas-workflow-orchestrator/packages/skills/_shared/references/stack-profiles.md +36 -0
  78. package/plugins/atlas-workflow-orchestrator/packages/skills/_shared/scripts/document_quality.mjs +252 -0
  79. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-backlog-generator/SKILL.md +7 -2
  80. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-direct-execute/SKILL.md +6 -2
  81. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-findings-repair/SKILL.md +11 -1
  82. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-plan-execute/SKILL.md +16 -2
  83. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-plan-handoff/SKILL.md +6 -4
  84. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-prd-interview/SKILL.md +7 -2
  85. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/SKILL.md +37 -2
  86. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  87. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  88. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  89. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  90. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-task-validator/SKILL.md +29 -14
  91. package/plugins/atlas-workflow-orchestrator/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  92. package/plugins/atlas-workflow-orchestrator/packages/templates/PRD_TEMPLATE.md +2 -1
  93. package/plugins/atlas-workflow-orchestrator/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  94. package/plugins/atlas-workflow-orchestrator/skills/_shared/references/stack-profiles.md +36 -0
  95. package/plugins/atlas-workflow-orchestrator/skills/_shared/scripts/document_quality.mjs +252 -0
  96. package/plugins/atlas-workflow-orchestrator/skills/atlas-backlog-generator/SKILL.md +7 -2
  97. package/plugins/atlas-workflow-orchestrator/skills/atlas-direct-execute/SKILL.md +6 -2
  98. package/plugins/atlas-workflow-orchestrator/skills/atlas-findings-repair/SKILL.md +11 -1
  99. package/plugins/atlas-workflow-orchestrator/skills/atlas-plan-execute/SKILL.md +16 -2
  100. package/plugins/atlas-workflow-orchestrator/skills/atlas-plan-handoff/SKILL.md +6 -4
  101. package/plugins/atlas-workflow-orchestrator/skills/atlas-prd-interview/SKILL.md +7 -2
  102. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/SKILL.md +37 -2
  103. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  104. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  105. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  106. package/plugins/atlas-workflow-orchestrator/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  107. package/plugins/atlas-workflow-orchestrator/skills/atlas-task-validator/SKILL.md +29 -14
  108. package/plugins/atlas-workflow-orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  109. package/plugins/atlas-workflow-orchestrator/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  110. package/plugins/atlas-workflow-orchestrator/templates/PRD_TEMPLATE.md +2 -1
  111. package/plugins/atlas-workflow-orchestrator/templates/STATE_FILE_SCHEMA.md +25 -1
@@ -33,8 +33,10 @@ Se faltar informação não bloqueante, gere o backlog com premissas marcadas e
33
33
  6. **Decompor em sprints:** transforme o objetivo em fatias verticais pequenas, cada uma com objetivo único, dependências e PRD futuro (`PRD_S<NN>_<slug>.md`).
34
34
  7. **Priorizar:** para cada sprint, preencha MoSCoW, ganho, esforço e prioridade usando a regra da seção 8.3 do template.
35
35
  8. **Selecionar próxima sprint:** escolha a primeira sprint executável respeitando dependências, DoR, MoSCoW, esforço x ganho e risco. Registre a justificativa na seção 20.
36
- 9. **Salvar artefato:** grave o backlog no path pedido ou, se não houver path, crie o diretório `.atlas/backlog/` no projeto consumidor e use `.atlas/backlog/BACKLOG_MESTRE_<slug>.md`.
37
- 10. **Validar antes de finalizar:** releia o arquivo salvo e confirme que não restaram placeholders acidentais, exceto campos conscientemente pendentes e marcados.
36
+ 9. **Atualização não destrutiva:** se o arquivo existe, compare antes/depois com `validateBacklogUpdate(before, after, { authorizedIds })` de `../_shared/scripts/document_quality.mjs`. `authorizedIds` contém somente IDs cuja mudança foi explicitamente decidida pelo usuário. Preserve demais IDs, linhas `done`, decisões `decidido|fechado|aprovado`, itens/sprints e ordem histórica.
37
+ 10. **Registrar alterações:** toda atualização acrescenta `## Registro de alterações` (data, IDs afetados, motivo e fonte). Não reescreva histórico anterior.
38
+ 11. **Salvar artefato:** grave o backlog no path pedido ou, se não houver path, crie o diretório `.atlas/backlog/` no projeto consumidor e use `.atlas/backlog/BACKLOG_MESTRE_<slug>.md`.
39
+ 12. **Validar antes de finalizar:** bloqueie se `validateBacklogUpdate` apontar sprint/decisão removida, sprint `done` alterada, enum inválido, ciclo de dependência, placeholder acidental ou falta de registro. Confirme também que dependências referenciam IDs existentes.
38
40
 
39
41
  ---
40
42
 
@@ -76,6 +78,7 @@ O backlog final deve:
76
78
  - Ter catálogo de fases preservado e adaptado apenas quando necessário.
77
79
  - Ter riscos, decisões e próxima sprint executável preenchidos.
78
80
  - Ser específico o bastante para gerar PRDs de sprint depois com `atlas-sprint-prd-generator`.
81
+ - Preservar histórico/IDs em update e passar validação de ciclos/enums/placeholders.
79
82
 
80
83
  ---
81
84
 
@@ -86,3 +89,5 @@ O backlog final deve:
86
89
  - Não inventar endpoints, tabelas, schemas, fornecedores, métricas ou responsabilidades como fatos. Quando forem hipóteses, marcar como premissa.
87
90
  - Não transformar o backlog em plano técnico de implementação. Código, classes e comandos entram no plano/PRD quando apropriado, não no backlog mestre.
88
91
  - Não deixar `[...]` ou placeholders óbvios no arquivo final, salvo quando o campo estiver deliberadamente pendente e explicado.
92
+ - Não renumerar IDs, reabrir/editar sprint `done`, alterar decisão fechada ou remover item não relacionado por conveniência editorial.
93
+ - Não ser acionada pelo orquestrador: permanece **explicit-only**, fora de qualquer cadeia automática.
@@ -149,6 +149,8 @@ For each task, keep a tiny task contract:
149
149
 
150
150
  Do not widen scope for opportunistic cleanup.
151
151
 
152
+ **Minimalism rung (per task, before writing):** prefer the minimal viable implementation that satisfies the obligation — reuse existing repo code/symbol before introducing a new abstraction; use a stdlib/native platform feature before a new dependency; avoid indirection, factory, wrapper, extra layer, config option, or extra file not required by an obligation or invariant. This rung constrains only new abstraction/indirection/file/dependency. It never reduces trust-boundary validation, error handling, data-loss handling, invariants, scenario/test coverage, or negative paths. When minimal and safe conflict, choose safe.
153
+
152
154
  Before the first concrete task, emit `task_started`. After the first workspace mutation, emit `first_write`.
153
155
 
154
156
  ### 4. Gate each task
@@ -175,6 +177,8 @@ After tasks and local gates pass, write `.atlas/state/<run_id>/<slice>.json` fol
175
177
 
176
178
  For direct execution, the state file is still the only validator input. Use the user-provided PRD/spec path as `plan_path` when no handoff plan exists, and include direct-contract anchors in `boundary_refs` such as `direct.O1`, `direct.invariant.permissions`, or `direct.risk.partial_failure`.
177
179
 
180
+ Persist the full direct contract using the additive state extension: `base_sha`, `head_sha`, `contract_kind: direct`, non-empty `obligations`, `invariants`, `scenario_probes`, `risk_probes`, `validation_map`, `task_evidence`, empty `repair_evidence`, `worktree_baseline` and `worktree_final`. Capture baseline before the first mutation and final immediately before handoff; `files_changed`/evidence must equal `base_sha...head_sha` + snapshot delta. Capture base from an explicit task/spec anchor or execution-start `HEAD`; never infer it from branch name. Recompute `head_sha` and `diff_stat` immediately before handoff. A direct state without obligations is invalid and must block.
181
+
178
182
  The state file is the only validator input. Validation is always **sibling**, on every host: this executor **never** dispatches `atlas-task-validator` itself and never validates its own work in the same context. After tasks and local gates pass and the state file is written, this executor **stops mutation** and returns `validator_handoff_required` with the `state_path`. The orchestrator then dispatches `atlas-task-validator` as the next isolated sibling phase, locks it via `atlas_lock_validator`, and — if the verdict is `fail` — dispatches `atlas-findings-repair` (not this executor) before the **2nd and last** validator.
179
183
 
180
184
  After writing the state file and before returning, emit `state_path_created` with the same `state_path`.
@@ -190,7 +194,7 @@ The verdict is consumed by the **orchestrator**, not by this executor:
190
194
 
191
195
  This executor only re-engages if the orchestrator explicitly re-dispatches it for a new slice. It must not "fix" observations and reopen a closed slice; real follow-up from an observation goes to the final report or backlog, not into an extra in-slice change.
192
196
 
193
- If isolated subagents are unavailable in the current environment, do not pretend the slice is validator-closed. Run a local self-check against the same contract, report `validator not run`, and mark residual risk explicitly.
197
+ If isolated subagents or MCP are unavailable, return `blocked` with the missing prerequisite and next safe action. Never replace cold validation with a local self-check or report `validator not run` as an accepted pipeline outcome.
194
198
 
195
199
  ## Stop Conditions
196
200
 
@@ -211,7 +215,7 @@ Keep final report short:
211
215
  - changed scope
212
216
  - files touched
213
217
  - validations run
214
- - validator verdict/cycles
218
+ - `validator_handoff_required` + `state_path`
215
219
  - blockers or residual risks
216
220
 
217
221
  Do not include the full internal contract unless the user asks.
@@ -49,6 +49,7 @@ Leia `atlas_run_state` como fonte primária do estado da run. O `state_path` con
49
49
  5. **Não despachar validator, review ou qualquer subagente.** O orquestrador faz isso.
50
50
  6. **Não iniciar terceiro ciclo.** Esta skill existe só entre validator 1 e validator 2.
51
51
  7. **Não trocar o `state_path`.** Atualize o arquivo original em lugar; redirecionar o boundary invalida a correlação do repair.
52
+ 8. **Não inventar correlação.** IDs devem existir no packet recebido, sem duplicatas; todo arquivo tocado pertence a pelo menos um `repair_evidence` recebido e nenhum arquivo extra é permitido.
52
53
 
53
54
  ## Fluxo
54
55
 
@@ -67,6 +68,8 @@ Leia do plano apenas o mínimo necessário:
67
68
  - Section 6 — contratos técnicos
68
69
  - Section 8 — checklist
69
70
 
71
+ Capture também `base_sha`, `head_sha`, `task_evidence`, `repair_evidence`, `worktree_baseline` e `worktree_final` do state.
72
+
70
73
  ### 2. Ler os findings recebidos
71
74
 
72
75
  Trabalhe somente com findings de severidade:
@@ -75,6 +78,8 @@ Trabalhe somente com findings de severidade:
75
78
  - `P1`
76
79
  - `P2`
77
80
 
81
+ Cada finding novo deve ter `id`, `failure_mode`, `evidence`, `recommendation` e `fix_validation`. `msg` é compatibilidade deprecated e não substitui esses campos.
82
+
78
83
  Se o pacote vier vazio, inconsistente ou sem finding reparável, pare em `blocked`.
79
84
 
80
85
  ### 3. Montar contrato mínimo de reparo
@@ -115,7 +120,11 @@ Se o finding persistir por falta de decisão de produto, dependência externa ou
115
120
 
116
121
  Ao terminar:
117
122
 
118
- - atualize o conteúdo do `state_path` original se a evidência do boundary mudou
123
+ - atualize `files_changed` com todo arquivo tocado, inclusive novo/adjacente
124
+ - recompute `head_sha` (`git rev-parse HEAD`) e `diff_stat`; preserve `base_sha`
125
+ - preserve `worktree_baseline` e recapture `worktree_final` após o repair; derive o boundary completo do delta entre snapshots
126
+ - acrescente `repair_evidence[]` no shape `{finding_id, files_touched, checks_run, status}`
127
+ - garanta que cada `repair_evidence.files_touched` esteja em `files_changed`
119
128
  - mantenha a mesma slice
120
129
  - não invente novo run state paralelo
121
130
 
@@ -128,6 +137,7 @@ Retorne saída curta e estruturada com:
128
137
  - `state_path`
129
138
  - `files_touched`
130
139
  - `checks_run`
140
+ - `repairs`: array `{finding_id, files_touched, checks_run, status: resolved|blocked}`
131
141
  - `residual_risk` (se houver)
132
142
 
133
143
  O orquestrador chamará `atlas_lock_validator(action=repair_complete, repair_run_id=..., state_path=<mesmo path original>)` e só então poderá despachar o validator final.
@@ -130,16 +130,30 @@ Create `.atlas/state/<run_id>/<slice>.json` following `packages/templates/STATE_
130
130
  {
131
131
  "run_id": "<run_id>",
132
132
  "slice": "<slice id>",
133
+ "base_sha": "<base commit explícito do plano/handoff>",
134
+ "head_sha": "<git rev-parse HEAD ao fechar a execução>",
135
+ "contract_kind": "plan",
133
136
  "tasks": ["T01"],
134
137
  "files_changed": ["relative/path.ext"],
135
138
  "diff_stat": "N files, +X -Y",
136
139
  "plan_path": ".atlas/plans/<id>.plan.md",
137
140
  "boundary_refs": ["§2.I1", "§6.1", "§8"],
141
+ "obligations": [],
142
+ "invariants": [{"id": "I1", "requirement": "<invariante>", "expected_evidence": ["<path/check>"]}],
143
+ "scenario_probes": [{"id": "S1", "scenario": "<cenário>", "expected": "<resultado>"}],
144
+ "risk_probes": [{"id": "R1", "risk": "<risco>", "probe": "<pergunta verificável>"}],
145
+ "validation_map": [{"obligation_ids": [], "checks": ["<comando>"], "status": "passed"}],
146
+ "task_evidence": [{"task": "T01", "files": ["relative/path.ext"], "checks": ["<comando>"], "result": "passed"}],
147
+ "repair_evidence": [],
148
+ "worktree_baseline": [{"path": "relative/preexisting.ext", "status": "M", "sha256": "<64 hex>"}],
149
+ "worktree_final": [{"path": "relative/preexisting.ext", "status": "M", "sha256": "<64 hex>"}],
138
150
  "executed_at": "ISO8601",
139
151
  "executor_skill": "atlas-plan-execute"
140
152
  }
141
153
  ```
142
154
 
155
+ Capture `base_sha` da referência explícita do plano/handoff; nunca infira pelo nome da branch. Antes da primeira mutação, capture `worktree_baseline`; imediatamente antes do handoff, capture `worktree_final`. `files_changed` e `task_evidence` representam exatamente `base_sha...head_sha` + delta entre snapshots. Dirty preexistente byte/status-idêntico fica fora; qualquer alteração posterior entra.
156
+
143
157
  Validation is always **sibling**, on every host. The validator is registered as a real subagent on every host, but this executor **never** dispatches it and never validates its own work. After tasks and local gates pass and the state file is written, this executor **stops mutation** and returns `validator_handoff_required` with the `state_path`. The orchestrator dispatches `atlas-task-validator` as the next isolated sibling phase, locks it via `atlas_lock_validator`, and — if the verdict is `fail` — dispatches `atlas-findings-repair` (not this executor) before the **2nd and last** validator.
144
158
 
145
159
  After writing the state file and before returning, emit `state_path_created` with the same `state_path`.
@@ -157,5 +171,5 @@ This executor does not parse the validator output — the **orchestrator** does,
157
171
 
158
172
  Never decide by substring matching prose. Once the slice is closed, do not edit code, tests, or boundary files just to satisfy an observation; that reopens the slice and forces an avoidable re-validation. Real follow-up from an observation goes to the final report or a backlog item, not into an extra in-slice change.
159
173
 
160
- ### 10. Report final outcome
161
- At the end of execution, report completed tasks, validations run, validator outcome, and any residual gaps.
174
+ ### 10. Report executor handoff
175
+ Report only completed tasks, local validations, files changed, and `validator_handoff_required` with `state_path`. Validator verdict/cycles and final residuals belong exclusively to the orchestrator's final report.
@@ -47,8 +47,8 @@ No workflow `full`, `atlas-plan-handoff` é autoria documental do agente princip
47
47
 
48
48
  ## Fluxo obrigatório
49
49
 
50
- 1. **Classificação da tarefa:** feature, ui, contract, navigation, shared, security, diagnostic, refactoring, testing. Leia `project-rules/index/<tipo>.md` e regras em `project-rules/rules/` (ou equivalente do repo ativo).
51
- 2. **Grounding no código:** confirme padrões, contratos e comandos locais (`flutter analyze` / `flutter test` com path do package) antes de inferir.
50
+ 1. **Classificação da tarefa:** feature, ui, contract, navigation, shared, security, diagnostic, refactoring, testing. Leia instruções reais aplicáveis do repo; `project-rules/` é apenas um formato possível, nunca requisito universal.
51
+ 2. **Grounding no código:** confirme padrões, contratos, manifests e comandos reais antes de inferir. Resolva baseline/perfis via `../_shared/references/stack-profiles.md` + `detectStackProfiles(project_root, declared_commands, boundary_paths)`; não presuma Flutter nem aplique perfil fora do package correspondente.
52
52
  3. **Decisões estáveis:** sanar bloqueios com perguntas ao usuário; registrar no plano (não recopiar tabela D* do PRD — referenciar `PRD §3`).
53
53
  4. **Escrita:** artefato markdown no path canônico `.atlas/plans/`. Teto orientativo ~250–350 linhas (até ~450 com slices).
54
54
 
@@ -112,7 +112,9 @@ Tarefas `#### T01.` … `#### TNN.` com schema de `BOUNDARY_PRD_PLAN.md` canôni
112
112
  - **Quality gates** (opcional em tasks críticas)
113
113
  - **Casos mínimos** (somente em tasks de teste)
114
114
 
115
- Última task típica: **Validação final** (`flutter analyze`, `flutter test`, passos manuais alinhados a **PRD §4–6**).
115
+ **Regra de minimalismo estrutural (autoria de task):** ao redigir `Mudança esperada`, prefira a forma mínima viável que cumpre o `Critério de done` reusar módulo/símbolo já existente no repo antes de introduzir nova abstração; usar stdlib/feature nativa antes de dependência nova; evitar indireção, factory, wrapper, camada ou opção de config não exigida por PRD/invariante. A regra recai **somente** sobre abstração/indireção/arquivo/dependência nova. **Nunca** reduz: validação de trust-boundary, error-handling, data-loss, invariantes §2, cobertura de cenário/teste e negative paths. Em dúvida entre enxuto e seguro, escolha seguro.
116
+
117
+ Última task típica: **Validação final** (checks reais da stack ativa e passos manuais alinhados a **PRD §4–6**). Flutter usa `flutter analyze/test`; Node e Python usam somente scripts/ferramentas declarados no repo/plano.
116
118
 
117
119
  ### 6. Contratos técnicos (só ambiguidade PRD → código)
118
120
 
@@ -126,7 +128,7 @@ Tarefas `#### T01.` … `#### TNN.` com schema de `BOUNDARY_PRD_PLAN.md` canôni
126
128
 
127
129
  - Critérios derivados de **PRD §6** + invariantes **§2** deste plano.
128
130
  - Título recomendado: `## 8. Validação e checklist (validator)`.
129
- - Comandos globais de analyze/test do package.
131
+ - Comandos globais aplicáveis ao package, derivados de manifests/scripts reais; nunca inventar `flutter`, `npm` ou `pytest`.
130
132
 
131
133
  ---
132
134
 
@@ -41,8 +41,11 @@ Ataque principalmente as seguintes seções do template de PRD:
41
41
  * **§5 Contrato funcional e invariantes:** `❌` se campos críticos não possuírem regras de formato (ex: decimais) ou se a regra de negócio for ambígua/impossível de verificar na codebase.
42
42
  * **§6 Critérios de aceite (negócio):** `❌` se o critério for subjetivo, não observável ou não testável.
43
43
 
44
- 3. **Perguntas por Rodada (AskUserQuestion):** Formule rodadas de no máximo 4 perguntas concisas via ferramenta nativa `AskUserQuestion`, com exatamente 3 opções e indicando a recomendada. **Pare o turno e aguarde a resposta.**
45
- 4. **Veredito Final:** emita o veredito de `Pronto para planejamento` quando zerar todos os `❌`.
44
+ 3. **Resolver mecanismo estruturado:** chame `atlas_capabilities`, leia `question_prompt` e use seu `mechanism`/shape. Nunca hardcode nome de ferramenta de host. Se o descriptor estiver ausente ou indisponível, bloqueie a rodada; não degrade para pergunta livre sem correlação.
45
+ 4. **Perguntas por rodada:** formule no máximo 4 perguntas concisas, exatamente 3 opções, recomendada explícita e `decision_id` D* estável. Antes de perguntar, use `pendingInterviewQuestions` de `../_shared/scripts/document_quality.mjs` para excluir decisões fechadas.
46
+ 5. **Persistência imediata:** ao receber respostas, grave-as no mesmo PRD antes de qualquer nova pergunta, preservando IDs/anchors e acrescentando histórico. Use `persistInterviewRound(prd_path, answers)`, que escreve via arquivo temporário + rename e valida readback; falha bloqueia. Nunca acumule respostas apenas no chat.
47
+ 6. **Reindexação:** releia o PRD salvo, reexecute o índice §3–§6 e recalcule perguntas pendentes. Decisão fechada não pode reaparecer em rodada posterior.
48
+ 7. **Veredito Final:** só emita `Pronto para planejamento` quando zerar todos os `❌`; no workflow, devolva controle ao orquestrador para reexecutar artifact/scan/TC.
46
49
 
47
50
  ---
48
51
 
@@ -55,6 +58,8 @@ Ataque principalmente as seguintes seções do template de PRD:
55
58
  §6 Aceite: ✅/⚠️/❌
56
59
  ```
57
60
 
61
+ O índice é materializado novamente após cada persistência; não reutilize índice anterior à resposta.
62
+
58
63
  ---
59
64
 
60
65
  ## Uso standalone vs protocolo interno no workflow (PRD D10/D11)
@@ -54,7 +54,7 @@ Base the review on three inputs:
54
54
 
55
55
  ### 1. Build the slice boundary first
56
56
  Before reviewing code, identify:
57
- * diff physical boundary (`git diff --name-only main...HEAD`).
57
+ * boundary físico do diff a partir do state/task ids; use a base configurada ou upstream e inclua mudanças não commitadas pertencentes à slice.
58
58
  * Section 2 - Invariants of Execution (contract).
59
59
  * Section 6 - Technical Contracts (signatures and shapes).
60
60
  * Section 8 - Validation and Checklist (QA criteria).
@@ -81,10 +81,43 @@ Ask what the implementation forgot:
81
81
  * **View & rendering:** inputs empty, null, partial, out of order, UI permission conditional.
82
82
  * **Contracts:** shape drift, enums, mappers, RLS server-side, i18n parity.
83
83
 
84
+ Aplique estes probes determinísticos a cada símbolo ou hunk alterado relevante:
85
+ * **Linha a linha:** leia cada hunk alterado e a função completa que o contém; construa entradas, estados, timings ou plataformas concretas capazes de provocar falha.
86
+ * **Comportamento removido:** para cada guard, validação, cleanup, error path ou teste removido/substituído, identifique o invariante protegido e prove onde o novo código o restabelece.
87
+ * **Rastreamento cross-file:** inspecione callers e callees quando assinaturas, shapes de retorno, erros, timing, ordem ou pré-condições mudarem.
88
+ * **Altitude:** confirme que a mudança corrige o componente proprietário do invariante, sem empilhar um caso especial local sobre um defeito compartilhado.
89
+ * **Regras aplicáveis:** inspecione arquivos de instruções do repo que governam os arquivos alterados. Reporte apenas violações exatas, com path da regra, texto da regra, linha violadora e impacto concreto.
90
+
91
+ Reuse, simplificação e eficiência só viram findings quando o diff atual cria custo comportamental, operacional ou de manutenção concreto. Não reporte preferências de estilo.
92
+
84
93
  ### 4. Distinguish current-diff findings from pre-existing issues
85
94
  Prefer findings attributable to the executed slice. Mark pre-existing issues as observations or separate notes to keep signals clean and actionable.
86
95
 
87
- ### 5. Output Expectations
96
+ ### 5. Verifique candidatos antes de reportar
97
+
98
+ Elimine duplicatas que descrevam o mesmo defeito no mesmo local. Classifique cada candidato restante como:
99
+ * `CONFIRMED` — evidência e cenário de falha alcançável sustentam o defeito.
100
+ * `REFUTED` — código, tipo, invariante ou guard prova que o candidato é falso ou já está tratado.
101
+ * `NEEDS_EVIDENCE` — o cenário é relevante, mas a evidência disponível não estabelece o defeito.
102
+
103
+ Apenas `CONFIRMED` vira finding. Descarte `REFUTED`. Mova `NEEDS_EVIDENCE` para `Perguntas Abertas ou Suposições`, sem apresentá-lo como defeito. Nunca mantenha um candidato apenas por ser plausível.
104
+
105
+ Antes de renderizar a saída, materialize os findings confirmados como JSON e execute o gate canônico Node `node scripts/classify_findings.mjs <findings.json>`. Cada item deve conter `severity`, `task_id`, `title`, `file`, `line`, `failure_mode`, `evidence`, `recommendation` e `fix_validation`. Saída não-zero bloqueia o relatório até o payload ser corrigido; é proibido ignorar o gate ou substituir campos ausentes por texto vazio. Array vazio é válido quando não há findings confirmados.
106
+
107
+ Node é o único requisito runtime deste gate e funciona em Linux/macOS/Windows. `scripts/classify_findings.py` permanece por uma release somente como wrapper compatível que delega ao Node; não é fonte canônica nem torna Python obrigatório.
108
+
109
+ ### 6. Recomende uma correção de causa raiz
110
+
111
+ Todo finding deve incluir exatamente uma recomendação principal de correção e uma validação que comprove a correção. A recomendação deve:
112
+ * atacar a causa raiz no componente proprietário do invariante violado;
113
+ * ser cirúrgica e permanecer no boundary revisado, salvo quando a evidência provar que o proprietário está fora dele;
114
+ * preservar contratos do plano, arquitetura e comportamento existente não implicado pelo finding;
115
+ * nomear concretamente componente, condição e comportamento esperado;
116
+ * ser a melhor correção sustentada pela evidência disponível, nunca uma alegação sem suporte de superioridade absoluta.
117
+
118
+ Não ofereça alternativas A/B. Não forneça patch completo nem altere código. Se a evidência for insuficiente para recomendar uma correção com segurança, classifique o candidato como `NEEDS_EVIDENCE` em vez de emitir finding.
119
+
120
+ ### 7. Output Expectations
88
121
 
89
122
  Return exactly this structure:
90
123
 
@@ -97,6 +130,8 @@ Return exactly this structure:
97
130
  - **Arquivo:** `relative/path.ext:line`
98
131
  - **Modo de falha:** [o que quebra e como]
99
132
  - **Evidência:** [o que suporta o finding]
133
+ - **Correção recomendada:** [uma correção cirúrgica na causa raiz]
134
+ - **Validação da correção:** [teste/check específico que comprova a resolução]
100
135
 
101
136
  ### P1 - <short title>
102
137
  [same shape]
@@ -34,6 +34,14 @@ Use these lenses to find hidden bugs in the executed slice. Apply only the relev
34
34
  - Is retry or re-entry behavior still coherent after this slice?
35
35
  - Did generated files, localization keys, imports, routes, RPC signatures, or schemas match the verified repo convention?
36
36
 
37
+ ## Mecânica da mudança
38
+
39
+ - Qual invariante cada guard, validação, cleanup, error path ou teste removido/substituído protegia, e onde ele foi restabelecido?
40
+ - Callers e callees alterados ainda concordam sobre pré-condições, shapes de retorno, erros, timing e ordem?
41
+ - A mudança corrige o componente proprietário do invariante ou adiciona um caso especial local frágil?
42
+ - Algum novo problema de reuse, simplificação ou eficiência tem custo comportamental, operacional ou de manutenção concreto?
43
+ - As instruções aplicáveis do repo expõem uma violação exata, atribuível a uma linha e com impacto concreto?
44
+
37
45
  ## Security and safety
38
46
 
39
47
  - Did the slice weaken permission, ownership, or visibility checks?
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ export const SEVERITY_ORDER = Object.freeze({ P0: 0, P1: 1, P2: 2, P3: 3 });
6
+ export const REQUIRED_TEXT_FIELDS = Object.freeze([
7
+ 'task_id', 'title', 'file', 'failure_mode', 'evidence', 'recommendation', 'fix_validation',
8
+ ]);
9
+
10
+ export function normalizeFinding(finding, index) {
11
+ if (!finding || typeof finding !== 'object' || Array.isArray(finding)) {
12
+ throw new Error(`Finding ${index} must be a JSON object`);
13
+ }
14
+ if (!(finding.severity in SEVERITY_ORDER)) {
15
+ throw new Error(`Finding ${index} has invalid severity: ${JSON.stringify(finding.severity)}`);
16
+ }
17
+ const missing = REQUIRED_TEXT_FIELDS.filter(
18
+ (field) => typeof finding[field] !== 'string' || !finding[field].trim(),
19
+ );
20
+ if (missing.length) throw new Error(`Finding ${index} missing required fields: ${missing.join(', ')}`);
21
+ if (!Number.isInteger(finding.line) || finding.line < 1) {
22
+ throw new Error(`Finding ${index} has invalid line: ${JSON.stringify(finding.line)}`);
23
+ }
24
+ return {
25
+ severity: finding.severity,
26
+ task_id: finding.task_id,
27
+ title: finding.title,
28
+ file: finding.file,
29
+ line: finding.line,
30
+ summary: typeof finding.summary === 'string' ? finding.summary : '',
31
+ failure_mode: finding.failure_mode,
32
+ evidence: finding.evidence,
33
+ recommendation: finding.recommendation,
34
+ fix_validation: finding.fix_validation,
35
+ diff_attributed: finding.diff_attributed !== false,
36
+ };
37
+ }
38
+
39
+ export function classifyFindings(payload) {
40
+ if (!Array.isArray(payload)) throw new Error('Findings input must be a JSON array');
41
+ return payload.map(normalizeFinding).sort((a, b) => (
42
+ SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]
43
+ || a.task_id.localeCompare(b.task_id)
44
+ || a.file.localeCompare(b.file)
45
+ || a.line - b.line
46
+ ));
47
+ }
48
+
49
+ export function run(argv = process.argv.slice(2)) {
50
+ if (argv.length !== 1) throw new Error('Usage: node classify_findings.mjs <findings.json>');
51
+ const payload = JSON.parse(fs.readFileSync(argv[0], 'utf8'));
52
+ process.stdout.write(`${JSON.stringify(classifyFindings(payload), null, 2)}\n`);
53
+ }
54
+
55
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
56
+ try { run(); } catch (error) {
57
+ process.stderr.write(`${error.message}\n`);
58
+ process.exitCode = 1;
59
+ }
60
+ }
@@ -1,56 +1,24 @@
1
1
  #!/usr/bin/env python3
2
- """Normalize raw findings into a severity-oriented review structure."""
2
+ """Wrapper legado: delega ao gate Node canônico por uma release."""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
- import argparse
7
- import json
8
6
  import pathlib
7
+ import subprocess
9
8
  import sys
10
- from typing import Any
11
-
12
- SEVERITY_ORDER = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
13
-
14
-
15
- def load_findings(path: pathlib.Path) -> list[dict[str, Any]]:
16
- payload = json.loads(path.read_text(encoding="utf-8"))
17
- if not isinstance(payload, list):
18
- raise ValueError("Findings input must be a JSON array")
19
- return payload
20
-
21
-
22
- def normalize_finding(finding: dict[str, Any]) -> dict[str, Any]:
23
- severity = finding.get("severity", "P2")
24
- if severity not in SEVERITY_ORDER:
25
- severity = "P2"
26
- return {
27
- "severity": severity,
28
- "task_id": finding.get("task_id", ""),
29
- "title": finding.get("title", ""),
30
- "file": finding.get("file", ""),
31
- "line": finding.get("line"),
32
- "summary": finding.get("summary", ""),
33
- "evidence": finding.get("evidence", ""),
34
- "diff_attributed": bool(finding.get("diff_attributed", True)),
35
- }
36
9
 
37
10
 
38
11
  def main() -> int:
39
- parser = argparse.ArgumentParser(description=__doc__)
40
- parser.add_argument("findings_json", help="Path to a JSON array of findings")
41
- args = parser.parse_args()
42
-
12
+ if len(sys.argv) != 2:
13
+ sys.stderr.write("Usage: python classify_findings.py <findings.json>\n")
14
+ return 1
15
+ script = pathlib.Path(__file__).with_name("classify_findings.mjs")
43
16
  try:
44
- normalized = [normalize_finding(item) for item in load_findings(pathlib.Path(args.findings_json))]
45
- except (FileNotFoundError, ValueError, json.JSONDecodeError) as exc:
46
- sys.stderr.write(f"{exc}\n")
17
+ return subprocess.run(["node", str(script), sys.argv[1]], check=False).returncode
18
+ except FileNotFoundError:
19
+ sys.stderr.write("Node.js ausente: requisito runtime do Atlas\n")
47
20
  return 1
48
21
 
49
- normalized.sort(key=lambda item: (SEVERITY_ORDER[item["severity"]], item["task_id"], item["file"], item["line"] or 0))
50
- json.dump(normalized, sys.stdout, indent=2)
51
- sys.stdout.write("\n")
52
- return 0
53
-
54
22
 
55
23
  if __name__ == "__main__":
56
24
  raise SystemExit(main())
@@ -16,6 +16,7 @@ Todo PRD gerado por esta skill deve declarar explicitamente a cadeia de execuç
16
16
  * Sprint ID: `S<NN>` (`S01`, `S02`, etc.).
17
17
  * Opcional: app/projeto alvo quando houver mais de uma fonte de backlog/roadmap.
18
18
  * Opcional: path de saída.
19
+ * Opcional: path explícito do backlog autoritativo. Quando fornecido, vence qualquer descoberta.
19
20
 
20
21
  *Se faltar o Sprint ID, peça antes de gerar.*
21
22
 
@@ -23,10 +24,11 @@ Todo PRD gerado por esta skill deve declarar explicitamente a cadeia de execuç
23
24
 
24
25
  ## Workflow Obrigatório
25
26
 
26
- 1. **Localizar Insumos:** Descubra a raiz do repo com `git rev-parse --show-toplevel`. Localize o template canônico em `<raiz-do-plugin>/packages/templates/PRD_TEMPLATE.md`. Localize backlog/roadmap no repo ativo (`**/BACKLOG_MESTRE*.md`).
27
- 2. **Extração da Sprint:** Leia a fonte de backlog/roadmap. Localize a sprint, extraindo fase-fonte, objetivo, dependências e filename do PRD.
28
- 3. **Inspecionar Código:** Busque no codebase por classes, tabelas, RPCs, mappers e rotas existentes que influenciam a feature.
29
- 4. **Redação do PRD:** Siga estritamente o layout enxuto e focado do `PRD_TEMPLATE.md` (teto orientativo de ~180-220 linhas), separando dores e regras de negócio de implementações de código.
27
+ 1. **Localizar Insumos:** Descubra a raiz do repo com `git rev-parse --show-toplevel`. Localize o template canônico em `<raiz-do-plugin>/packages/templates/PRD_TEMPLATE.md`. Localize backlogs candidatos (`**/BACKLOG_MESTRE*.md`) sem escolher por heurística silenciosa.
28
+ 2. **Fechar autoridade:** use `../_shared/scripts/document_quality.mjs#resolveSprintAuthority` com precedência fixa: path explícito → backlog canônico referenciado pelo artefato/input → único candidato contendo o Sprint ID. Zero match bloqueia. Múltiplos matches sem autoridade, mesmo com conteúdo parecido, bloqueiam com paths conflitantes e `next_action` para informar o path.
29
+ 3. **Extração da Sprint:** leia somente a fonte autoritativa. Extraia fase-fonte, objetivo, dependências e filename do PRD; registre no PRD o path + anchor exato da linha/seção do backlog.
30
+ 4. **Inspecionar Código:** Busque no codebase por contratos reais que influenciam a feature e registre anchors estáveis (`path:símbolo` ou `path:linha`) nas referências; não copie implementação para o PRD.
31
+ 5. **Redação/atualização:** siga `PRD_TEMPLATE.md`. Ao atualizar, preserve IDs `D*`, decisões fechadas, anchors e histórico; novos IDs são append-only. Mudança deliberada em D* exige decisão explícita e registro histórico.
30
32
 
31
33
  ### Resolução Canônica de Templates
32
34
 
@@ -57,6 +59,7 @@ Todo PRD criado ou atualizado por esta skill deve incluir, perto do topo e sem s
57
59
 
58
60
  * **Status final:** `Aprovado para implementação`. Setar **automaticamente** ao finalizar a geração — é o status que o gate TC do orquestrador exige (`required_status=Aprovado para implementação`) para o PRD avançar no pipeline. Não deixar `Draft` (trava o gate e força correção manual). O sinal de determinismo que sustenta o avanço é o `atlas_scan_prd` (varredura de ambiguidade) + entrevista quando houver padrões bloqueantes — não o campo Status, que é marcador documental.
59
61
  * **Data:** ISO `YYYY-MM-DD` (hoje).
62
+ * **Autoridade:** `Relacionado`/`Referências` inclui backlog autoritativo + anchor da sprint e anchors de código/contrato usados.
60
63
  * **Escopo:** Lista fechada de capacidades funcionais.
61
64
  * **UX:** Cobrir caminhos de `loading`, `empty`, `error`, `success` e `permission` sob a perspectiva do usuário.
62
65
  * **Critérios de Aceite:** Binários e observáveis, divididos conforme `PRD_TEMPLATE.md` em: **Produto**, **UX**, **Dados** e **Regressão de produto**.
@@ -34,9 +34,16 @@ Read the JSON file at `.atlas/state/<run_id>/<slice>.json` using the schema in `
34
34
  3. **Executed task ids** — `tasks`.
35
35
  4. **Boundary refs** — `boundary_refs`.
36
36
  5. **Explicit cold-review note** — you did not observe implementation; read current code only.
37
+ 6. **Deterministic boundary** — `base_sha`, `head_sha`, `contract_kind`, and all evidence/probe arrays.
38
+ 7. **Working-tree delta** — compare `worktree_baseline`/`worktree_final` and current tree; unchanged preexisting dirt stays outside, later mutations must be evidenced.
39
+ 8. **Repair correlation** — on attempt 2, correlate every target finding id with `repair_evidence` in the same state path.
37
40
 
38
41
  Do not accept inline contract, copied diff, or pasted task lists as the validation boundary. If `state_path` is missing, unreadable, or lacks any required field, return JSON with `verdict: "fail"` and one P1 finding for `Input insuficiente: <missing item>`.
39
42
 
43
+ Compatibilidade: state legado mínimo sem `contract_kind` só é aceito quando `executor_skill=atlas-plan-execute`; nesse caso o plano continua autoritativo. State de `atlas-direct-execute` exige extensão completa e `obligations` não vazio.
44
+
45
+ Antes de validar código, compare `base_sha...head_sha`, `HEAD`, snapshot final atual e delta `worktree_baseline→worktree_final` com `files_changed`/evidências. Não infira base pelo nome da branch. Divergência gera `boundary_violations` e finding P1 estruturado.
46
+
40
47
  ---
41
48
 
42
49
  ## Resolução Canônica de Templates
@@ -79,23 +86,24 @@ Do not accept inline contract, copied diff, or pasted task lists as the validati
79
86
  3. **For each relevant Section 6 Contract:** verify signature, behavior, and returned shape where applicable.
80
87
  4. **For each relevant Section 8 checklist item:** mark it pass or fail with evidence.
81
88
  5. **Perform cross-task checks** for shared state, missing required args, route order, partial failure handling, and UI/backend permission mismatch.
82
- 6. **Apply universal baseline checks** below. Do not invent new mandatory criteria outside the plan and baseline.
89
+ 6. **Aplique baseline + perfis ativos** abaixo. Resolva os perfis por manifests/comandos reais conforme `../_shared/references/stack-profiles.md`; não invente critérios fora do plano, baseline e perfis ativos.
83
90
  7. **Do not patch files or propose diffs.** Suggested fix must fit in 1-2 lines of text.
84
91
 
85
92
  ---
86
93
 
87
- ## Universal Baseline
94
+ ## Baseline universal + perfis
95
+
96
+ Fonte compartilhada: `../_shared/references/stack-profiles.md`. Execute `detectStackProfiles(project_root, declared_commands, boundary_paths)` de `../_shared/scripts/document_quality.mjs`; aplique cada entrada de `boundaries` somente aos arquivos daquele package.
97
+
98
+ Sempre aplique baseline universal: segurança/permissões, boundary/contratos, erros/falhas parciais, concorrência/reentrada, cleanup/estado stale, integridade de dados/input e checks realmente declarados.
99
+
100
+ Ative regras específicas somente quando o perfil retornar `true`:
88
101
 
89
- Always apply these checks:
90
- * **Naming cross-layer:** New read methods use `get*` prefix. Mutation uses explicit verbs (`create`, `update`, `delete`, `add`, `remove`). Concepts keep consistent root names across layers.
91
- * **State lifecycle:** Shared stores or controllers reused across modes or routes must reset previous mode state in `init()` or transition.
92
- * **Navigation args:** Argument resolvers validate required fields; navigation passes all required ids (no empty placeholder `''`).
93
- * **Partial failure paths:** Multi-step mutations surface partial persistence clearly if a later step fails.
94
- * **Backend and UI gate match:** Sensitive mutations require server-side enforcement. UI gating alone is insufficient (Page reads `canManage` from Store).
95
- * **Route registration:** Literal routes are registered before parameterized routes (`/:id`, `/:id/edit`) under the same prefix.
96
- * **Localization:** New localization keys must exist in every required locale file; generated l10n is clean.
97
- * **Analyzer:** `flutter analyze` (or stack equivalent) returns zero issues for touched files in boundary.
98
- * **Casts and nullability:** Remote payload casts use safe defensive patterns; nulos in collections treated with `?? []`.
102
+ - `flutter_dart`: lifecycle Flutter, rotas/args, null-safety/casts, l10n, analyze/test; GetX somente se dependência/import/regra real confirmar GetX.
103
+ - `node_typescript`: handles/promises, validação runtime, ESM/CJS/exports/tipos e scripts Node reais.
104
+ - `python`: context managers/cleanup, exceções/async, typing/parsing e ferramentas Python declaradas.
105
+
106
+ Monorepo pode ativar múltiplos perfis, sempre restritos ao boundary correspondente. Fixture Node sem sinal Flutter não recebe regra Flutter/GetX.
99
107
 
100
108
  ---
101
109
 
@@ -110,10 +118,15 @@ Return strict JSON as the final output. Do not wrap it in Markdown and do not pr
110
118
  "verdict": "pass | fail | pass_with_observations",
111
119
  "findings": [
112
120
  {
121
+ "id": "F-001",
113
122
  "severity": "P0|P1|P2|P3",
114
123
  "file": "string",
115
- "line": 0,
116
- "msg": "string"
124
+ "line": 1,
125
+ "failure_mode": "string",
126
+ "evidence": "string",
127
+ "recommendation": "string",
128
+ "fix_validation": "string",
129
+ "msg": "string (deprecated; derivado por uma release)"
117
130
  }
118
131
  ],
119
132
  "observations": [
@@ -134,6 +147,8 @@ Return strict JSON as the final output. Do not wrap it in Markdown and do not pr
134
147
 
135
148
  `dispatch_token` must equal `validator_recovery.expected_dispatch_token`. `findings`, `observations`, and `boundary_violations` must always be arrays. Use empty arrays when there are no items.
136
149
 
150
+ IDs são únicos, obrigatórios no formato `F-NNN` e estáveis nos dois ciclos. Severity é estritamente `P0|P1|P2|P3`. No segundo ciclo, confirme por ID que `repair_evidence` registra arquivos, checks e `status: resolved`; finding não correlacionado permanece P1. O MCP rejeita shape incompleto e `pass`/`pass_with_observations` quando há P0/P1.
151
+
137
152
  **Proof-of-work (`challenge_response`).** If `validator_recovery.challenge` is not `null`, it carries `{ file, algo: "sha256" }` — a boundary file you must have read access to. Compute the sha256 of that file's raw bytes (`shasum -a 256 "<challenge.file>"`) and return the hex (first token) in `challenge_response`. If `challenge` is `null`, return `null`. Never fabricate the hash: the orchestrator recomputes it from disk and blocks the slice (`challenge_failed`) on mismatch. This is a *mechanical* attestation that the verdict touched real boundary bytes — it closes the laziest bypass (claiming `pass` with no read at all); it does **not** by itself prove you read and understood the code (hashing a file does not require loading its content). Reading the boundary remains your obligation. It is not a non-forgeable isolation proof either (the MCP shares one stdio caller). Challenge failures are bounded per attempt: past the cap the slot closes terminally (`challenge_exhausted`), which usually signals path resolution diverging from the consumer root.
138
153
 
139
154
  ---