atlas-workflow 0.9.1 → 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 (106) hide show
  1. package/VERSION +1 -1
  2. package/build/tests/classify-findings.test.mjs +20 -0
  3. package/build/tests/etapa3.test.mjs +161 -0
  4. package/build/tests/test_classify_findings.py +79 -0
  5. package/hosts/opencode/.opencode/agents/atlas-findings-repair.md +4 -0
  6. package/hosts/opencode/.opencode/agents/atlas-task-validator.md +18 -1
  7. package/hosts/opencode/.opencode/atlas/VERSION +1 -1
  8. package/hosts/opencode/.opencode/atlas/orchestrator/README.md +6 -4
  9. package/hosts/opencode/.opencode/atlas/orchestrator/commands/workflow.md +1 -1
  10. package/hosts/opencode/.opencode/atlas/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  11. package/hosts/opencode/.opencode/atlas/packages/mcp-server/package.json +1 -1
  12. package/hosts/opencode/.opencode/atlas/packages/mcp-server/server.js +446 -14
  13. package/hosts/opencode/.opencode/atlas/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  14. package/hosts/opencode/.opencode/atlas/packages/templates/PRD_TEMPLATE.md +2 -1
  15. package/hosts/opencode/.opencode/atlas/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  16. package/hosts/opencode/.opencode/skills/_shared/references/stack-profiles.md +36 -0
  17. package/hosts/opencode/.opencode/skills/_shared/scripts/document_quality.mjs +252 -0
  18. package/hosts/opencode/.opencode/skills/atlas-backlog-generator/SKILL.md +7 -2
  19. package/hosts/opencode/.opencode/skills/atlas-direct-execute/SKILL.md +6 -2
  20. package/hosts/opencode/.opencode/skills/atlas-findings-repair/SKILL.md +11 -1
  21. package/hosts/opencode/.opencode/skills/atlas-plan-execute/SKILL.md +16 -2
  22. package/hosts/opencode/.opencode/skills/atlas-plan-handoff/SKILL.md +6 -4
  23. package/hosts/opencode/.opencode/skills/atlas-prd-interview/SKILL.md +7 -2
  24. package/hosts/opencode/.opencode/skills/atlas-slice-review/SKILL.md +37 -2
  25. package/hosts/opencode/.opencode/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  26. package/hosts/opencode/.opencode/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  27. package/hosts/opencode/.opencode/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  28. package/hosts/opencode/.opencode/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  29. package/hosts/opencode/.opencode/skills/atlas-task-validator/SKILL.md +29 -14
  30. package/hosts/opencode/.opencode/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  31. package/hosts/pi/.pi/agents/atlas-direct-execute.md +6 -2
  32. package/hosts/pi/.pi/agents/atlas-findings-repair.md +15 -1
  33. package/hosts/pi/.pi/agents/atlas-plan-execute.md +16 -2
  34. package/hosts/pi/.pi/agents/atlas-slice-review.md +37 -2
  35. package/hosts/pi/.pi/agents/atlas-task-validator.md +18 -1
  36. package/hosts/pi/atlas/VERSION +1 -1
  37. package/hosts/pi/atlas/orchestrator/README.md +6 -4
  38. package/hosts/pi/atlas/orchestrator/commands/workflow.md +1 -1
  39. package/hosts/pi/atlas/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  40. package/hosts/pi/atlas/packages/mcp-server/package.json +1 -1
  41. package/hosts/pi/atlas/packages/mcp-server/server.js +446 -14
  42. package/hosts/pi/atlas/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  43. package/hosts/pi/atlas/packages/templates/PRD_TEMPLATE.md +2 -1
  44. package/hosts/pi/atlas/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  45. package/hosts/pi/skills/_shared/references/stack-profiles.md +36 -0
  46. package/hosts/pi/skills/_shared/scripts/document_quality.mjs +252 -0
  47. package/hosts/pi/skills/atlas-backlog-generator/SKILL.md +7 -2
  48. package/hosts/pi/skills/atlas-direct-execute/SKILL.md +6 -2
  49. package/hosts/pi/skills/atlas-findings-repair/SKILL.md +11 -1
  50. package/hosts/pi/skills/atlas-plan-execute/SKILL.md +16 -2
  51. package/hosts/pi/skills/atlas-plan-handoff/SKILL.md +6 -4
  52. package/hosts/pi/skills/atlas-prd-interview/SKILL.md +7 -2
  53. package/hosts/pi/skills/atlas-slice-review/SKILL.md +37 -2
  54. package/hosts/pi/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  55. package/hosts/pi/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  56. package/hosts/pi/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  57. package/hosts/pi/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  58. package/hosts/pi/skills/atlas-task-validator/SKILL.md +29 -14
  59. package/hosts/pi/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  60. package/package.json +1 -1
  61. package/plugins/atlas-workflow-orchestrator/.codex/agents/atlas-findings-repair.toml +1 -1
  62. package/plugins/atlas-workflow-orchestrator/.codex/agents/atlas-task-validator.toml +1 -1
  63. package/plugins/atlas-workflow-orchestrator/.codex-plugin/plugin.json +1 -1
  64. package/plugins/atlas-workflow-orchestrator/VERSION +1 -1
  65. package/plugins/atlas-workflow-orchestrator/agents/atlas-findings-repair.md +4 -0
  66. package/plugins/atlas-workflow-orchestrator/agents/atlas-task-validator.md +18 -1
  67. package/plugins/atlas-workflow-orchestrator/orchestrator/README.md +6 -4
  68. package/plugins/atlas-workflow-orchestrator/orchestrator/commands/workflow.md +1 -1
  69. package/plugins/atlas-workflow-orchestrator/orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  70. package/plugins/atlas-workflow-orchestrator/packages/mcp-server/package.json +1 -1
  71. package/plugins/atlas-workflow-orchestrator/packages/mcp-server/server.js +446 -14
  72. package/plugins/atlas-workflow-orchestrator/packages/skills/_shared/references/stack-profiles.md +36 -0
  73. package/plugins/atlas-workflow-orchestrator/packages/skills/_shared/scripts/document_quality.mjs +252 -0
  74. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-backlog-generator/SKILL.md +7 -2
  75. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-direct-execute/SKILL.md +6 -2
  76. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-findings-repair/SKILL.md +11 -1
  77. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-plan-execute/SKILL.md +16 -2
  78. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-plan-handoff/SKILL.md +6 -4
  79. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-prd-interview/SKILL.md +7 -2
  80. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/SKILL.md +37 -2
  81. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  82. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  83. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  84. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  85. package/plugins/atlas-workflow-orchestrator/packages/skills/atlas-task-validator/SKILL.md +29 -14
  86. package/plugins/atlas-workflow-orchestrator/packages/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  87. package/plugins/atlas-workflow-orchestrator/packages/templates/PRD_TEMPLATE.md +2 -1
  88. package/plugins/atlas-workflow-orchestrator/packages/templates/STATE_FILE_SCHEMA.md +25 -1
  89. package/plugins/atlas-workflow-orchestrator/skills/_shared/references/stack-profiles.md +36 -0
  90. package/plugins/atlas-workflow-orchestrator/skills/_shared/scripts/document_quality.mjs +252 -0
  91. package/plugins/atlas-workflow-orchestrator/skills/atlas-backlog-generator/SKILL.md +7 -2
  92. package/plugins/atlas-workflow-orchestrator/skills/atlas-direct-execute/SKILL.md +6 -2
  93. package/plugins/atlas-workflow-orchestrator/skills/atlas-findings-repair/SKILL.md +11 -1
  94. package/plugins/atlas-workflow-orchestrator/skills/atlas-plan-execute/SKILL.md +16 -2
  95. package/plugins/atlas-workflow-orchestrator/skills/atlas-plan-handoff/SKILL.md +6 -4
  96. package/plugins/atlas-workflow-orchestrator/skills/atlas-prd-interview/SKILL.md +7 -2
  97. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/SKILL.md +37 -2
  98. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/references/scenario-lenses.md +8 -0
  99. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/scripts/classify_findings.mjs +60 -0
  100. package/plugins/atlas-workflow-orchestrator/skills/atlas-slice-review/scripts/classify_findings.py +9 -41
  101. package/plugins/atlas-workflow-orchestrator/skills/atlas-sprint-prd-generator/SKILL.md +7 -4
  102. package/plugins/atlas-workflow-orchestrator/skills/atlas-task-validator/SKILL.md +29 -14
  103. package/plugins/atlas-workflow-orchestrator/skills/atlas-workflow-orchestrator/SKILL.md +22 -17
  104. package/plugins/atlas-workflow-orchestrator/templates/BACKLOG_MESTRE_TEMPLATE.md +14 -3
  105. package/plugins/atlas-workflow-orchestrator/templates/PRD_TEMPLATE.md +2 -1
  106. package/plugins/atlas-workflow-orchestrator/templates/STATE_FILE_SCHEMA.md +25 -1
@@ -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
  ---
@@ -21,7 +21,7 @@ Orquestra pipelines de desenvolvimento de features no projeto Atlas, automatizan
21
21
  Três modos **canônicos de execução** — `full`, `direct`, `execute` (PRD §5 D1) — mais o modo `interview-only`, que permanece **separado** (entrevista sem execução; PRD D2, não é colapsado em `full`).
22
22
 
23
23
  - **`full`** — pipeline completo: PRD → validação → entrevista (se necessário) → **plano (artefato obrigatório)** → executor → review (opcional)
24
- - **`direct`** — pipeline enxuto: PRD → validação → entrevista (se necessário) → executor → review (opcional). **Não produz plano de handoff** — a diferença real para `full` é exatamente essa.
24
+ - **`direct`** — pipeline enxuto: PRD → validação → entrevista (se necessário) → `atlas-direct-execute` → review (opcional). **Não produz plano de handoff** — a diferença real para `full` é exatamente essa.
25
25
  - **`execute`** — recebe um **`PLAN_*.md` pronto** e o executa **sem gerar plano** (PRD D1). Entrada = caminho de plano; reverifica o artefato + conformidade de template e despacha `plan_execute` direto. Não regera nem replaneja: ajustes de plano pedem `full`. `atlas_assert_after_plan` (gate pós-plano do `full`) **não se aplica** em `execute` — o plano já é o input; o equivalente é a reverificação na entrada (PRD D13). **Não há alias `plan`**: usar `plan` como modo é ambíguo com planejamento documental e deve ser rejeitado como modo inválido.
26
26
  - **`interview-only`** — entrevista direta (ex: brainstorm, resolução de decisões). Entrevista **sem execução**: não usa `guarantee_level` no fluxo (não há execução de código a garantir). Permanece modo separado (PRD D2).
27
27
 
@@ -51,7 +51,7 @@ Três modos **canônicos de execução** — `full`, `direct`, `execute` (PRD §
51
51
  → Gera PRD de indicação, força entrevista, plano, executor
52
52
 
53
53
  /workflow interview-only brainstorm "que tal dark mode?"
54
- Entrevista direto, sem PRD prévio
54
+ Cria draft mínimo pelo template canônico, valida o path e entrevista esse PRD; sem execução
55
55
 
56
56
  /workflow execute plan "/path/to/PLAN_S05_login.md"
57
57
  → Reverifica o plano (artifact + TC), executa direto via plan_execute + validador frio. Não gera plano.
@@ -102,7 +102,7 @@ Executar **antes** de iniciar o pipeline. Se qualquer item falhar, **parar e rep
102
102
  Ação: instalar/ativar o plugin ou corrigir o pacote atlas-* disponível no host
103
103
  ```
104
104
  **PROIBIDO o fallback "implementação direta" / "contratos equivalentes inline".** Não existe caminho onde o orquestrador faz plano ou código no próprio fio. Emulação inline e fallback direto são a falha-raiz que esta skill proíbe — se não há sub-agent, **para**. (Gate G7.)
105
- 8. **Rejeitar conflito de modo:** se o pedido tiver `full`/`direct` junto com "sem patch", "sem editar código", "planejamento apenas", "handoff only" ou equivalente, **pare antes de gerar artefatos**. `full`/`direct` executam `plan_execute`; não existe interpretação plan-only implícita.
105
+ 8. **Rejeitar conflito de modo:** se o pedido tiver `full`/`direct` junto com "sem patch", "sem editar código", "planejamento apenas", "handoff only" ou equivalente, **pare antes de gerar artefatos**. `full` executa `atlas-plan-execute`; `direct` executa `atlas-direct-execute`; não existe interpretação plan-only implícita.
106
106
  9. **Declarar o plano de execução** (1 bloco curto): `run_id`, modo, **ids exatos de cada sub-agent**, sequência de fases, artefatos esperados e tools MCP que sustentarão cada gate. Só então iniciar a Fase 1.
107
107
 
108
108
  ---
@@ -120,7 +120,7 @@ O pipeline é **fire-and-continue**: uma vez iniciado, o orquestrador avança fa
120
120
 
121
121
  **Após entrevista**: reexecuta os gates afetados (`atlas_verify_artifact`/`atlas_scan_prd`/TC) e **retoma o pipeline (plano→execução) automaticamente**, sem nova confirmação.
122
122
 
123
- A única interação legítima com o usuário é **dentro de uma fase** — o `AskUserQuestion` da entrevista para resolver ambiguidade de produto. Resolver ambiguidade ≠ pedir permissão pra avançar. Terminada a fase, o pipeline segue sozinho até o próximo gate duro ou o output final.
123
+ A única interação legítima com o usuário é **dentro de uma fase** — o mecanismo estruturado `question_prompt` devolvido por `atlas_capabilities`, usado pela entrevista para resolver ambiguidade de produto. Resolver ambiguidade ≠ pedir permissão pra avançar. Terminada a fase, respostas são persistidas no PRD, gates são reexecutados e o pipeline segue sozinho.
124
124
 
125
125
  ## Papel do orquestrador (fronteira de determinismo pela mutação de código)
126
126
 
@@ -129,7 +129,7 @@ O orquestrador **coordena a execução**, não implementa código — maestro qu
129
129
  - **ANTES do plano validado — autoria documental livre no fio principal.** Pode autorar PRD, entrevistar e escrever `PLAN_*.md` direto; fases documentais não exigem sub-agent (documento não muta o produto). **Ao finalizar um PRD inline, estampar `| Status | Aprovado para implementação |`** — é o `required_status` do gate TC; sem isso o PRD sai `Draft` e trava o TC em rodadas de correção.
130
130
  - **DEPOIS do plano validado (`atlas_verify_artifact` + TC `passed`) — mãos atadas fortes.** Não edita mais PRD/plano/código nem roda comando mutante; só coordena (despachar sub-agent, ler artefato pra verificar gate, ecoar banner, montar output).
131
131
 
132
- Execução de código é **sempre** sub-agent `plan_execute` (blocking, um por vez) + validador frio `task_validator` (Gate G9/G7 — detalhe na tabela de gates). Dispatch blocking: despacha → espera retorno → verifica gate → próxima fase. Nunca dois sub-agents simultâneos.
132
+ Execução de código é **sempre** sub-agent executor do modo (`atlas-plan-execute` em `full`/`execute`; `atlas-direct-execute` em `direct`), mantendo `phase: plan_execute`, + validador frio `task_validator` (Gate G9/G7). Dispatch blocking: despacha → espera retorno → verifica gate → próxima fase. Nunca dois sub-agents simultâneos.
133
133
 
134
134
  ### Verbo de dispatch é host-agnóstico (não assuma "Agent tool")
135
135
 
@@ -180,9 +180,9 @@ Regras inegociáveis. Violação = parar, não contornar.
180
180
 
181
181
  ## Fluxo de execução
182
182
 
183
- ### [EXEC] — passo comum de execução + validação (idêntico em `full`/`direct`/`execute`)
183
+ ### [EXEC] — passo comum de execução + validação
184
184
 
185
- `atlas_lock_dispatch(action=start, phase=plan_execute)`; despachar `plan_execute` como sub-agent blocking (lê `PLAN_*.md` em `full`/`execute`, PRD em `direct`). O executor emite checkpoints G12; sem retorno/progresso, chamar `atlas_lock_dispatch(action=status, phase=plan_execute)` e tratar `executor_bootstrap_timeout`/`executor_progress_timeout` como `stalled`/retry — nunca como execução em andamento. O executor retorna `validator_handoff_required` com `state_path`; o MCP só abre o slot após o checkpoint `state_path_created` para esse mesmo `state_path`. Validação sempre **sibling**: `atlas_lock_validator(action=start)`, despachar **um** `task_validator`, exigir no output o `dispatch_token` do slot e fechar com `validator_run_id` + `dispatch_token`. Em `fail`: `repair_start`, despachar `atlas-findings-repair` com `{state_path, findings, validator_attempt, repair_run_id, repair_budget: 1}`, exigir atualização do mesmo `state_path`, fechar com `repair_run_id` e rodar o **2º e último** validator. `passed`/`passed_with_observations` são terminais aprovados; status diferente bloqueia review e output completed.
185
+ `atlas_lock_dispatch(action=start, phase=plan_execute)` em todos os modos; despachar como sub-agent blocking o `routing.executor_skill` devolvido pelo preflight: `atlas-plan-execute` em `full`/`execute`, `atlas-direct-execute` em `direct`. O executor emite checkpoints G12; sem retorno/progresso, chamar `atlas_lock_dispatch(action=status, phase=plan_execute)` e tratar `executor_bootstrap_timeout`/`executor_progress_timeout` como `stalled`/retry — nunca como execução em andamento. O executor retorna `validator_handoff_required` com `state_path`; o MCP só abre o slot após o checkpoint `state_path_created` para esse mesmo `state_path`. Validação sempre **sibling**: `atlas_lock_validator(action=start)`, despachar **um** `task_validator`, exigir no output o `dispatch_token` do slot e fechar com `validator_run_id` + `dispatch_token`. Em `fail`: `repair_start`, despachar `atlas-findings-repair` com `{state_path, findings, validator_attempt, repair_run_id, repair_budget: 1}`, exigir atualização do mesmo `state_path`, fechar com `repair_run_id` e rodar o **2º e último** validator. `passed`/`passed_with_observations` são terminais aprovados; status diferente bloqueia review e output completed.
186
186
 
187
187
  ### Full mode
188
188
 
@@ -225,8 +225,9 @@ Entrada: um **`PLAN_*.md` pronto**. Artefatos esperados: (plano já existe) →
225
225
 
226
226
  ### Interview-only mode
227
227
 
228
- 1. Entrevista direta (sem PRD anterior) invoca o id resolvido para `prd_interview`.
229
- 2. Gera PRD esboço (opcional).
228
+ 1. Se a entrada já for PRD válido, usar seu path. Se for `brainstorm`, criar primeiro um draft mínimo em disco com `packages/templates/PRD_TEMPLATE.md`, preservando as 6 seções canônicas e registrando o brainstorm em contexto/objetivo.
229
+ 2. Verificar o draft com `atlas_verify_artifact` e `atlas_verify_template_conformance(artifact_type=prd)`; path ausente/inválido bloqueia.
230
+ 3. Invocar `prd_interview` no fio principal com `prd_path` válido; persistir respostas no mesmo artefato e reverificar.
230
231
 
231
232
  > `interview-only` é entrevista **sem execução**: não há fase `plan_execute` nem `guarantee_level` no fluxo (nada de código a garantir). A autoria do esboço é documental e livre.
232
233
 
@@ -245,9 +246,10 @@ O scan é **determinístico** e roda **dentro do MCP** (`atlas_scan_prd`): a lis
245
246
  Detalhe do caminho que a "Princípio de continuação automática" exige para decisão pendente de **qualquer fonte** (scan/entrevista/validação de plano/`PERGUNTAS_EM_ABERTO.md`/`DISCUSSAO_*.md`/backlog — a fonte não muda o tratamento):
246
247
 
247
248
  1. **Garantir o PRD primeiro.** Em `full`/`direct`, se o PRD não existe, **gerar o PRD draft** com as decisões marcadas. A entrevista é **PRD-scoped**: roda **sobre** o PRD, nunca antes. Detectar decisão não antecipa nem pula a geração do PRD.
248
- 2. **Disparar `atlas-prd-interview`** sobre o PRD — resolve via `AskUserQuestion` (interação dentro da fase, não pedido de permissão).
249
- 3. **Propagar** ao PRD/plano/DEC/registro de origem.
250
- 4. **Reexecutar** os gates afetados (`atlas_verify_artifact`/`atlas_scan_prd`/TC) e **continuar** automaticamente.
249
+ 2. **Disparar `atlas-prd-interview`** sobre o PRD — resolve via `atlas_capabilities.question_prompt`, sem hardcode de host.
250
+ 3. **Persistir após cada rodada** no mesmo PRD, reindexar §3–§6 e não repetir D* fechada.
251
+ 4. **Propagar** ao PRD/plano/DEC/registro de origem.
252
+ 5. **Reexecutar** os gates afetados (`atlas_verify_artifact`/`atlas_scan_prd`/TC) e **continuar** automaticamente.
251
253
 
252
254
  Marcar TBD e adiar só se o usuário pedir **explicitamente** — nunca por iniciativa do orquestrador.
253
255
 
@@ -326,13 +328,16 @@ Se `full` gerou `PLAN_*.md` mas não despachou `plan_execute`, o cabeçalho deve
326
328
 
327
329
  ## Skills envolvidas
328
330
 
331
+ `atlas-backlog-generator` aparece apenas para descoberta do catálogo: é **explicit-only** e nunca integra `full`/`direct`/`execute`/`interview-only`. A cadeia automática começa em PRD/input já fornecido.
332
+
329
333
  | Skill | Entrada | Saída (artefato) |
330
334
  |-------|---------|------------------|
331
- | `atlas-backlog-generator` | ideia/prompt/conversa/briefing | `BACKLOG_MESTRE_*.md` |
335
+ | `atlas-backlog-generator` (**explicit-only**) | pedido explícito de backlog | `BACKLOG_MESTRE_*.md` |
332
336
  | `atlas-sprint-prd-generator` | sprint_id/indicação | `PRD_*.md`, decisions_found |
333
337
  | `atlas-prd-interview` | prd_path, ambiguities | `PRD_*.md` atualizado, decisions |
334
338
  | `atlas-plan-handoff` | prd_path | `PLAN_*.md` |
335
- | `atlas-plan-execute` | plan_path (full / **execute**) ou prd_path (direct) | diff de código, evidência |
339
+ | `atlas-plan-execute` | plan_path (`full` / `execute`) | diff de código, evidência, `state_path` |
340
+ | `atlas-direct-execute` | prd_path/spec/task (`direct`) | diff de código, evidência, `state_path` |
336
341
  | `atlas-slice-review` | diff/output | review_feedback |
337
342
 
338
343
  **Sub-agent frio (Gate G4):** `atlas-task-validator` é verificado no pré-flight pelo orquestrador e sempre roda isolado como **sub-agent irmão (sibling)**, em todos os hosts: despachado pelo orquestrador a partir do `state_path` retornado pelo executor. A topologia é sempre sibling — o executor nunca despacha o validador.
@@ -356,11 +361,11 @@ Se o MCP não responder ou reportar drift, o pacote está inválido: abortar no
356
361
  ```
357
362
  orquestrador
358
363
  ├─ MCP ping + preflight → atlas_ping + atlas_preflight (G10)
359
- ├─ PRD → sub-agent → atlas_verify_artifact (G1)
364
+ ├─ PRD → autoria documental no pai → atlas_verify_artifact (G1)
360
365
  ├─ scan → atlas_scan_prd (G5) + TC → entrevista se bloqueado ou --interview
361
- ├─ PLANO → lock_dispatch + sub-agent → atlas_verify_artifact + atlas_verify_template_conformance
366
+ ├─ PLANO → autoria documental no pai → atlas_verify_artifact + atlas_verify_template_conformance
362
367
  ├─ G11 → atlas_assert_after_plan → próxima ação obrigatória = plan_execute
363
- ├─ EXECUÇÃO → atlas_lock_dispatch + sub-agent plan_execute
368
+ ├─ EXECUÇÃO → atlas_lock_dispatch + sub-agent atlas-plan-execute
364
369
  ├─ VALIDAÇÃO → lock_validator + task-validator irmão
365
370
  │ └─ fail → findings-repair (budget 1, mesmo state_path) → validator final
366
371
  └─ REVIEW → atlas_lock_dispatch + sub-agent slice_review (se --review)
@@ -181,6 +181,8 @@ For each task, keep a tiny task contract:
181
181
 
182
182
  Do not widen scope for opportunistic cleanup.
183
183
 
184
+ **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.
185
+
184
186
  Before the first concrete task, emit `task_started`. After the first workspace mutation, emit `first_write`.
185
187
 
186
188
  ### 4. Gate each task
@@ -207,6 +209,8 @@ After tasks and local gates pass, write `.atlas/state/<run_id>/<slice>.json` fol
207
209
 
208
210
  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`.
209
211
 
212
+ 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.
213
+
210
214
  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.
211
215
 
212
216
  After writing the state file and before returning, emit `state_path_created` with the same `state_path`.
@@ -222,7 +226,7 @@ The verdict is consumed by the **orchestrator**, not by this executor:
222
226
 
223
227
  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.
224
228
 
225
- 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.
229
+ 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.
226
230
 
227
231
  ## Stop Conditions
228
232
 
@@ -243,7 +247,7 @@ Keep final report short:
243
247
  - changed scope
244
248
  - files touched
245
249
  - validations run
246
- - validator verdict/cycles
250
+ - `validator_handoff_required` + `state_path`
247
251
  - blockers or residual risks
248
252
 
249
253
  Do not include the full internal contract unless the user asks.
@@ -32,6 +32,10 @@ O orquestrador passa obrigatoriamente `state_path`, findings estruturados, `vali
32
32
  - Não replanejar
33
33
  - Não ampliar escopo
34
34
  - Atualizar o `state_path` original em lugar; não trocar o boundary para outro arquivo
35
+ - Consumir IDs/recommendations estruturadas; persistir correlação em `repair_evidence`
36
+ - Preservar `worktree_baseline`, recapturar `worktree_final` e incluir exatamente todo arquivo tocado em `files_changed`; recomputar `head_sha` e `diff_stat`
37
+ - Aceitar somente IDs recebidos; cada arquivo tocado deve estar atribuído a um finding recebido, sem IDs/arquivos extras ou duplicados
38
+ - Devolver `repairs[]` com `finding_id`, arquivos, checks e status
35
39
  - Ao terminar, devolver `repair_complete` ou `blocked`
36
40
 
37
41
 
@@ -85,6 +89,7 @@ Leia `atlas_run_state` como fonte primária do estado da run. O `state_path` con
85
89
  5. **Não despachar validator, review ou qualquer subagente.** O orquestrador faz isso.
86
90
  6. **Não iniciar terceiro ciclo.** Esta skill existe só entre validator 1 e validator 2.
87
91
  7. **Não trocar o `state_path`.** Atualize o arquivo original em lugar; redirecionar o boundary invalida a correlação do repair.
92
+ 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.
88
93
 
89
94
  ## Fluxo
90
95
 
@@ -103,6 +108,8 @@ Leia do plano apenas o mínimo necessário:
103
108
  - Section 6 — contratos técnicos
104
109
  - Section 8 — checklist
105
110
 
111
+ Capture também `base_sha`, `head_sha`, `task_evidence`, `repair_evidence`, `worktree_baseline` e `worktree_final` do state.
112
+
106
113
  ### 2. Ler os findings recebidos
107
114
 
108
115
  Trabalhe somente com findings de severidade:
@@ -111,6 +118,8 @@ Trabalhe somente com findings de severidade:
111
118
  - `P1`
112
119
  - `P2`
113
120
 
121
+ Cada finding novo deve ter `id`, `failure_mode`, `evidence`, `recommendation` e `fix_validation`. `msg` é compatibilidade deprecated e não substitui esses campos.
122
+
114
123
  Se o pacote vier vazio, inconsistente ou sem finding reparável, pare em `blocked`.
115
124
 
116
125
  ### 3. Montar contrato mínimo de reparo
@@ -151,7 +160,11 @@ Se o finding persistir por falta de decisão de produto, dependência externa ou
151
160
 
152
161
  Ao terminar:
153
162
 
154
- - atualize o conteúdo do `state_path` original se a evidência do boundary mudou
163
+ - atualize `files_changed` com todo arquivo tocado, inclusive novo/adjacente
164
+ - recompute `head_sha` (`git rev-parse HEAD`) e `diff_stat`; preserve `base_sha`
165
+ - preserve `worktree_baseline` e recapture `worktree_final` após o repair; derive o boundary completo do delta entre snapshots
166
+ - acrescente `repair_evidence[]` no shape `{finding_id, files_touched, checks_run, status}`
167
+ - garanta que cada `repair_evidence.files_touched` esteja em `files_changed`
155
168
  - mantenha a mesma slice
156
169
  - não invente novo run state paralelo
157
170
 
@@ -164,6 +177,7 @@ Retorne saída curta e estruturada com:
164
177
  - `state_path`
165
178
  - `files_touched`
166
179
  - `checks_run`
180
+ - `repairs`: array `{finding_id, files_touched, checks_run, status: resolved|blocked}`
167
181
  - `residual_risk` (se houver)
168
182
 
169
183
  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.
@@ -164,16 +164,30 @@ Create `.atlas/state/<run_id>/<slice>.json` following `packages/templates/STATE_
164
164
  {
165
165
  "run_id": "<run_id>",
166
166
  "slice": "<slice id>",
167
+ "base_sha": "<base commit explícito do plano/handoff>",
168
+ "head_sha": "<git rev-parse HEAD ao fechar a execução>",
169
+ "contract_kind": "plan",
167
170
  "tasks": ["T01"],
168
171
  "files_changed": ["relative/path.ext"],
169
172
  "diff_stat": "N files, +X -Y",
170
173
  "plan_path": ".atlas/plans/<id>.plan.md",
171
174
  "boundary_refs": ["§2.I1", "§6.1", "§8"],
175
+ "obligations": [],
176
+ "invariants": [{"id": "I1", "requirement": "<invariante>", "expected_evidence": ["<path/check>"]}],
177
+ "scenario_probes": [{"id": "S1", "scenario": "<cenário>", "expected": "<resultado>"}],
178
+ "risk_probes": [{"id": "R1", "risk": "<risco>", "probe": "<pergunta verificável>"}],
179
+ "validation_map": [{"obligation_ids": [], "checks": ["<comando>"], "status": "passed"}],
180
+ "task_evidence": [{"task": "T01", "files": ["relative/path.ext"], "checks": ["<comando>"], "result": "passed"}],
181
+ "repair_evidence": [],
182
+ "worktree_baseline": [{"path": "relative/preexisting.ext", "status": "M", "sha256": "<64 hex>"}],
183
+ "worktree_final": [{"path": "relative/preexisting.ext", "status": "M", "sha256": "<64 hex>"}],
172
184
  "executed_at": "ISO8601",
173
185
  "executor_skill": "atlas-plan-execute"
174
186
  }
175
187
  ```
176
188
 
189
+ 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.
190
+
177
191
  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.
178
192
 
179
193
  After writing the state file and before returning, emit `state_path_created` with the same `state_path`.
@@ -191,5 +205,5 @@ This executor does not parse the validator output — the **orchestrator** does,
191
205
 
192
206
  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.
193
207
 
194
- ### 10. Report final outcome
195
- At the end of execution, report completed tasks, validations run, validator outcome, and any residual gaps.
208
+ ### 10. Report executor handoff
209
+ 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.
@@ -82,7 +82,7 @@ Base the review on three inputs:
82
82
 
83
83
  ### 1. Build the slice boundary first
84
84
  Before reviewing code, identify:
85
- * diff physical boundary (`git diff --name-only main...HEAD`).
85
+ * 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.
86
86
  * Section 2 - Invariants of Execution (contract).
87
87
  * Section 6 - Technical Contracts (signatures and shapes).
88
88
  * Section 8 - Validation and Checklist (QA criteria).
@@ -109,10 +109,43 @@ Ask what the implementation forgot:
109
109
  * **View & rendering:** inputs empty, null, partial, out of order, UI permission conditional.
110
110
  * **Contracts:** shape drift, enums, mappers, RLS server-side, i18n parity.
111
111
 
112
+ Aplique estes probes determinísticos a cada símbolo ou hunk alterado relevante:
113
+ * **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.
114
+ * **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.
115
+ * **Rastreamento cross-file:** inspecione callers e callees quando assinaturas, shapes de retorno, erros, timing, ordem ou pré-condições mudarem.
116
+ * **Altitude:** confirme que a mudança corrige o componente proprietário do invariante, sem empilhar um caso especial local sobre um defeito compartilhado.
117
+ * **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.
118
+
119
+ 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.
120
+
112
121
  ### 4. Distinguish current-diff findings from pre-existing issues
113
122
  Prefer findings attributable to the executed slice. Mark pre-existing issues as observations or separate notes to keep signals clean and actionable.
114
123
 
115
- ### 5. Output Expectations
124
+ ### 5. Verifique candidatos antes de reportar
125
+
126
+ Elimine duplicatas que descrevam o mesmo defeito no mesmo local. Classifique cada candidato restante como:
127
+ * `CONFIRMED` — evidência e cenário de falha alcançável sustentam o defeito.
128
+ * `REFUTED` — código, tipo, invariante ou guard prova que o candidato é falso ou já está tratado.
129
+ * `NEEDS_EVIDENCE` — o cenário é relevante, mas a evidência disponível não estabelece o defeito.
130
+
131
+ 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.
132
+
133
+ 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.
134
+
135
+ 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.
136
+
137
+ ### 6. Recomende uma correção de causa raiz
138
+
139
+ 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:
140
+ * atacar a causa raiz no componente proprietário do invariante violado;
141
+ * ser cirúrgica e permanecer no boundary revisado, salvo quando a evidência provar que o proprietário está fora dele;
142
+ * preservar contratos do plano, arquitetura e comportamento existente não implicado pelo finding;
143
+ * nomear concretamente componente, condição e comportamento esperado;
144
+ * ser a melhor correção sustentada pela evidência disponível, nunca uma alegação sem suporte de superioridade absoluta.
145
+
146
+ 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.
147
+
148
+ ### 7. Output Expectations
116
149
 
117
150
  Return exactly this structure:
118
151
 
@@ -125,6 +158,8 @@ Return exactly this structure:
125
158
  - **Arquivo:** `relative/path.ext:line`
126
159
  - **Modo de falha:** [o que quebra e como]
127
160
  - **Evidência:** [o que suporta o finding]
161
+ - **Correção recomendada:** [uma correção cirúrgica na causa raiz]
162
+ - **Validação da correção:** [teste/check específico que comprova a resolução]
128
163
 
129
164
  ### P1 - <short title>
130
165
  [same shape]