@pathbit/agentdevkit 0.0.15 → 0.0.17

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 (40) hide show
  1. package/.pbai4devs/INSTRUCTIONS.md +1 -1
  2. package/.pbai4devs/README.md +1 -1
  3. package/.pbai4devs/scripts/inspecionar-projeto/SCRIPT.mjs +3 -2
  4. package/.pbai4devs/scripts/inspecionar-projeto/tests/TEST.mjs +18 -4
  5. package/.pbai4devs/scripts/lib/README.md +3 -0
  6. package/.pbai4devs/scripts/lib/state-path.mjs +20 -0
  7. package/.pbai4devs/scripts/sincronizar-agentes/README.md +1 -1
  8. package/.pbai4devs/scripts/sincronizar-agentes/SCRIPT.mjs +5 -3
  9. package/.pbai4devs/scripts/sincronizar-agentes/tests/COEXISTENCE.mjs +5 -5
  10. package/.pbai4devs/scripts/sincronizar-agentes/tests/HUMAN_OWNERSHIP.mjs +1 -1
  11. package/.pbai4devs/scripts/sincronizar-agentes/tests/MANAGED_CONTENT.mjs +9 -9
  12. package/.pbai4devs/scripts/sincronizar-agentes/tests/TEST.mjs +31 -6
  13. package/.pbai4devs/scripts/testar-maturidade/SCRIPT.mjs +6 -4
  14. package/.pbai4devs/scripts/testar-maturidade/tests/TEST.mjs +4 -3
  15. package/.pbai4devs/scripts/verificar-recursos/SCRIPT.mjs +5 -3
  16. package/.pbai4devs/scripts/verificar-recursos/tests/TEST.mjs +15 -7
  17. package/.pbai4devs/skills/produto/criar-design-doc/SKILL.md +1 -1
  18. package/.pbai4devs/skills/produto/criar-prd/SKILL.md +1 -1
  19. package/.pbai4devs/skills/produto/criar-ux-ui/SKILL.md +1 -1
  20. package/.pbai4devs/skills/projeto/configurar-projeto/SKILL.md +1 -1
  21. package/.pbai4devs/skills/projeto/proximos-passos/SKILL.md +1 -1
  22. package/.pbai4devs/skills/projeto/sincronizar-agentes/SKILL.md +1 -1
  23. package/.pbai4devs/skills/specs/criar-spec/SKILL.md +1 -1
  24. package/.pbai4devs/skills/specs/implementar-spec/SKILL.md +1 -1
  25. package/.pbai4devs/templates/entrypoints/AGENTS.md +1 -1
  26. package/.pbai4devs/templates/gitignore/local.ignore +2 -0
  27. package/.pbai4devs/templates/gitignore/shared.ignore +2 -0
  28. package/CHANGELOG.md +11 -0
  29. package/docs/guides/troubleshooting.md +9 -1
  30. package/docs/guides/workflow.md +1 -1
  31. package/docs/maintainers/maintenance.md +13 -6
  32. package/docs/specs/README.md +2 -0
  33. package/docs/specs/ci-resilience/SPEC.md +30 -0
  34. package/docs/specs/state-directory/SPEC.md +22 -0
  35. package/package.json +1 -1
  36. package/src/cli.mjs +2 -2
  37. package/src/config.mjs +2 -1
  38. package/src/i18n.mjs +15 -0
  39. package/src/install.mjs +152 -15
  40. /package/.pbai4devs/{estado → state}/README.md +0 -0
@@ -6,7 +6,7 @@ description: Cria uma spec de incremento, esclarecendo requisitos e dúvidas com
6
6
  # Criar spec
7
7
 
8
8
  Antes de escrever, aplique o inventário e plano de `atualizar-documentacao`.
9
- Leia os caminhos em `.pbai4devs/estado/configuracao/ESTADO.md`. Exija PRD/design
9
+ Leia os caminhos em `.pbai4devs/state/configuracao/ESTADO.md`. Exija PRD/design
10
10
  aprovados e UX/UI aprovado ou não aplicável com justificativa aprovada.
11
11
  Confira evidências, atualidade e decisões essenciais ao incremento; se faltar
12
12
  algo, encaminhe à etapa correspondente antes de escrever a spec.
@@ -5,7 +5,7 @@ description: Planeja e implementa uma spec aprovada, acompanhando tarefas e crit
5
5
 
6
6
  # Implementar spec
7
7
 
8
- Leia `.pbai4devs/estado/configuracao/ESTADO.md`. Exija spec, PRD e design aprovados;
8
+ Leia `.pbai4devs/state/configuracao/ESTADO.md`. Exija spec, PRD e design aprovados;
9
9
  UX/UI aprovado ou não aplicável com justificativa aprovada. Confira evidências,
10
10
  atualidade, decisões essenciais e vínculos com o roadmap; resolva pendências
11
11
  antes de implementar.
@@ -15,5 +15,5 @@ cliente em `.pbai4devs/COMPATIBILIDADE.md`.
15
15
 
16
16
  Use o `README.md` do projeto para seu contexto. Os clientes escolhidos têm
17
17
  apontamentos; scripts, ferramentas e modelos permanecem na origem compartilhada.
18
- Respeite a seleção em `.pbai4devs/estado/agentdevkit.json`. Para alterá-la, use
18
+ Respeite a seleção em `.pbai4devs/state/agentdevkit.json`. Para alterá-la, use
19
19
  `agents` na CLI; não deduza o agente ativo pelo aplicativo ou pelas pastas.
@@ -6,5 +6,7 @@
6
6
  /.pbai4devs/espelhos.conf
7
7
  /.pbai4devs/estado/agentdevkit.json
8
8
  /.pbai4devs/estado/derived.json
9
+ /.pbai4devs/state/agentdevkit.json
10
+ /.pbai4devs/state/derived.json
9
11
  {{ROOTS}}
10
12
  {{OUTPUTS}}
@@ -6,6 +6,8 @@
6
6
  /espelhos.conf
7
7
  /estado/agentdevkit.json
8
8
  /estado/derived.json
9
+ /state/agentdevkit.json
10
+ /state/derived.json
9
11
 
10
12
  # Downloads e launchers de ferramentas
11
13
  /tools/bin/
package/CHANGELOG.md CHANGED
@@ -4,6 +4,17 @@ description: Alterações verificáveis por versão do AgentDevKit.
4
4
 
5
5
  # Changelog
6
6
 
7
+ ## 0.0.17 — 2026-11-13
8
+
9
+ - A pasta compartilhada de estado passa a se chamar `.pbai4devs/state`.
10
+ - Instalações existentes migram os dados sem alterar o índice ou o ignore.
11
+
12
+ ## 0.0.16 — 2026-11-13
13
+
14
+ - Testes portáteis distribuídos entre jobs para Windows e macOS.
15
+ - Diagnósticos de subprocessos e espera do CI melhorados para releases.
16
+ - Instruções para recuperar o artefato da tentativa correta do CI.
17
+
7
18
  ## 0.0.15 — 2026-11-13
8
19
 
9
20
  - Especialistas e skills para arquitetura, backend, frontend, QA e performance.
@@ -73,11 +73,19 @@ Os backups são locais e ignorados; não substituem o controle de versão.
73
73
 
74
74
  ## Estado ou apontamentos inconsistentes
75
75
 
76
+ Se a instalação ainda usa `.pbai4devs/estado`, execute `agentdevkit update`
77
+ para migrar os dados e atualizar os scripts juntos. Se `estado` e `state`
78
+ coexistirem, compare e preserve as duas pastas antes de resolver o conflito;
79
+ o kit não escolhe nem sobrescreve uma delas automaticamente.
80
+ Se a configuração apontar para caminhos dentro da pasta antiga, atualize
81
+ esses caminhos para `.pbai4devs/state` antes de tentar novamente. O kit não
82
+ reescreve as decisões do projeto.
83
+
76
84
  `missing`, `modified` e `outdated` em `issues` indicam arquivo ausente,
77
85
  conteúdo alterado ou derivação pendente. Use `sync --check` para inspecionar;
78
86
  se as alterações da origem forem intencionais, execute `sync` e confira de novo.
79
87
 
80
- Se `.pbai4devs/estado/agentdevkit.json` estiver inválido, recupere um backup
88
+ Se `.pbai4devs/state/agentdevkit.json` estiver inválido, recupere um backup
81
89
  local coerente com os arquivos correspondentes. O estado pessoal não é
82
90
  versionado. Não invente hashes nem apague o estado para ocultar conflitos;
83
91
  peça ao agente para comparar as fontes e planejar o reparo com `init`/`sync`.
@@ -56,7 +56,7 @@ Neste momento quero apenas preparar os agentes; não crie produto ou aplicação
56
56
 
57
57
  Quando o produto começar, combine os caminhos dos documentos no estado de
58
58
  configuração. Não presuma que todo projeto usa as mesmas pastas de documentos.
59
- O registro é `.pbai4devs/estado/configuracao/ESTADO.md`.
59
+ O registro é `.pbai4devs/state/configuracao/ESTADO.md`.
60
60
 
61
61
  ## 3. Definir produto e experiência
62
62
 
@@ -19,22 +19,26 @@ Resultados e capturas de verificação permanecem ignorados.
19
19
 
20
20
  ## Verificar sem desperdiçar CI
21
21
 
22
- O CI tem quatro perfis:
22
+ O CI verifica Linux e distribui a portabilidade em grupos independentes:
23
23
 
24
24
  | Perfil | Responsabilidade |
25
25
  | --- | --- |
26
26
  | Linux / Node 24 | Fontes, produto, infraestrutura, lint e pacote real. |
27
- | Windows / Node 24 | Portabilidade da CLI, arquivos e runtime. |
28
- | macOS / Node 24 | Portabilidade da CLI, arquivos e runtime. |
27
+ | Windows / Node 24 | CLI, projetos, recursos e layout em jobs separados. |
28
+ | macOS / Node 24 | Os mesmos grupos de portabilidade em jobs separados. |
29
29
  | Linux / Node 26 | Smoke de compatibilidade. |
30
30
 
31
31
  O perfil macOS usa o runner padrão `macos-15-intel`. O label `macos-latest`
32
32
  usa ARM64 e pode ter filas diferentes; confira os [runners disponíveis][runners]
33
33
  antes de mudar a arquitetura. Provas locais devem informar a arquitetura usada.
34
34
 
35
- A distribuição real é testada uma vez no perfil completo. Os outros perfis
36
- validam seus riscos específicos. Execuções antigas da mesma referência podem
35
+ A distribuição real é testada uma vez no perfil completo. Todos os grupos de
36
+ Windows e macOS precisam passar para aprovar o CI. Cada grupo tem seu próprio
37
+ log e limite, o que facilita identificar o teste que falhou. Execuções antigas
38
+ da mesma referência podem
37
39
  ser canceladas quando substituídas, sem cancelar uma publicação em andamento.
40
+ Novas suítes devem integrar um grupo portátil ou registrar uma justificativa
41
+ explícita para executar somente no perfil completo.
38
42
 
39
43
  O workflow [Security tools smoke][security-ci] instala os três scanners com
40
44
  pins revisados em Linux, macOS e Windows. Depois analisa fixtures locais sem
@@ -81,7 +85,10 @@ Também envia o mesmo pacote ao [npm público e GitHub Packages](packages.md),
81
85
  confere a integridade nos dois destinos e testa versão, instalação, diagnóstico
82
86
  e sincronização. O consumo pelo npm é anônimo; pelo GitHub, autenticado.
83
87
 
84
- Se o artifact expirou, reexecute o CI original do push e depois a release.
88
+ Se o artifact expirou ou um job do CI falhou, use **Re-run all jobs** no CI
89
+ original do push e aguarde todos os jobs. **Re-run failed jobs** pode manter o
90
+ pacote de uma tentativa anterior, que a release não aceita. Depois reexecute
91
+ a release.
85
92
  Uma execução manual de CI serve para diagnóstico, mas não substitui essa
86
93
  procedência. Uma release existente não é sobrescrita.
87
94
 
@@ -19,6 +19,8 @@ description: Incrementos verificáveis do AgentDevKit.
19
19
  - [Ecossistema de segurança](security-ecosystem/SPEC.md): fluxos e scanners locais.
20
20
  - [Ecossistema de desenvolvimento](development-ecosystem/SPEC.md):
21
21
  especialistas, colaboração e provas.
22
+ - [Confiabilidade da pipeline](ci-resilience/SPEC.md): testes e releases.
23
+ - [Pasta de estado](state-directory/SPEC.md): migração segura para `state`.
22
24
  - [Integração sem substituição][additive]: acréscimos em arquivos existentes.
23
25
  - [Compatibilidade com projetos reais][oss]: projetos públicos e exemplos reproduzíveis.
24
26
  - [Ignore do projeto](project-ignore/SPEC.md): preservar o arquivo da raiz.
@@ -0,0 +1,30 @@
1
+ ---
2
+ description: Execução portátil e publicação confiáveis após falhas do CI.
3
+ ---
4
+
5
+ # Confiabilidade da pipeline
6
+
7
+ As verificações devem identificar a causa das falhas e oferecer margem para
8
+ runners de velocidades diferentes, sem reduzir a cobertura nem liberar um
9
+ pacote antes da aprovação de todos os jobs.
10
+
11
+ ## Critérios de aceite
12
+
13
+ - AC-001: Os testes portáteis executam em grupos independentes no Windows e
14
+ no macOS; uma falha em qualquer grupo reprova o CI. O comando local continua
15
+ executando todos os grupos e as suítes críticas permanecem cobertas.
16
+ - AC-002: Processos de teste e publicação reportam erros e sinais úteis sem
17
+ expor credenciais. Tempo esgotado continua sendo falha.
18
+ - AC-003: A release aguarda o CI pelo período configurado com margem para a
19
+ duração e a fila; continua exigindo o artefato do commit e da tentativa
20
+ aprovados e não aceita CI falho ou de outra origem.
21
+ - AC-004: Linux, Windows e macOS executam as verificações do CI real; os dois
22
+ registros recebem e verificam o mesmo pacote aprovado, se houver release.
23
+ - AC-005: A documentação explica os perfis e como repetir todos os jobs ao
24
+ recuperar o artefato de uma tentativa anterior.
25
+
26
+ ## Verificação
27
+
28
+ Execute testes de regressão dos limites, falhas, grupos e publicação, além do
29
+ perfil completo local. Acompanhe os runners reais e a release até a conclusão;
30
+ registre resultados e revisão independente no gate de entrega.
@@ -0,0 +1,22 @@
1
+ ---
2
+ description: Nome em inglês para a pasta de estado compartilhado.
3
+ ---
4
+
5
+ # Pasta de estado
6
+
7
+ A pasta de primeiro nível passa de `.pbai4devs/estado` para
8
+ `.pbai4devs/state`. Ela contém estado de instalação e configuração, não
9
+ memória de conversas. Os nomes internos permanecem iguais.
10
+
11
+ ## Critérios de aceite
12
+
13
+ - AC-001: Instalações novas usam `state` e recursos, documentação, exclusões
14
+ e pacote apontam para ela, sem expor estado local no pacote ou no Git.
15
+ - AC-002: A atualização de instalações antigas preserva seleção, idioma,
16
+ decisões, conteúdo humano e permissões; conflitos e links inseguros não
17
+ causam perda ou sobrescrita silenciosa.
18
+ - AC-003: Simulação, repetição, falhas e recuperação preservam arquivos,
19
+ índice Git e `.gitignore` do projeto. Scripts independentes identificam
20
+ instalações antigas e novas de forma coerente.
21
+ - AC-004: Testes locais, CI em Linux, Windows e macOS e revisão independente
22
+ verificam o comportamento e os limites da migração.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pathbit/agentdevkit",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "description": "Shared skills, specifications and workflows for AI coding agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.mjs CHANGED
@@ -2,7 +2,7 @@ import { existsSync } from 'node:fs';
2
2
  import { resolve, join } from 'node:path';
3
3
  import { createInterface } from 'node:readline/promises';
4
4
  import { spawnSync } from 'node:child_process';
5
- import { packageInfo } from './config.mjs';
5
+ import { packageInfo, statePath, legacyStatePath } from './config.mjs';
6
6
  import { text, normalizeLanguage, explainError } from './i18n.mjs';
7
7
  import { resolveTarget, loadState, planInstallation, applyPlan, inspect } from './install.mjs';
8
8
  import { getNextSteps } from './next.mjs';
@@ -169,7 +169,7 @@ export async function main(argv = process.argv.slice(2), context = {}) {
169
169
  }
170
170
  print(result, options, output); return exitCode;
171
171
  } catch (error) {
172
- const result = { ok: false, command: options.command || 'help', version: packageInfo.version, language, clients, target, message: explainError(language, error.code), error: { code: error.code || 'E_OPERATION', detail: error.message }, next: getNextSteps({ command: 'error', language, target, installed: existsSync(join(target, '.pbai4devs/estado/agentdevkit.json')) }) };
172
+ const result = { ok: false, command: options.command || 'help', version: packageInfo.version, language, clients, target, message: explainError(language, error.code), error: { code: error.code || 'E_OPERATION', detail: error.message }, next: getNextSteps({ command: 'error', language, target, installed: existsSync(join(target, statePath)) || existsSync(join(target, legacyStatePath)) }) };
173
173
  if (!options.json) result.message += ` (${error.code || 'E_OPERATION'})`;
174
174
  print(result, options, output); return error.exitCode || 1;
175
175
  }
package/src/config.mjs CHANGED
@@ -5,7 +5,8 @@ import { fileURLToPath } from 'node:url';
5
5
  export const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
6
6
  export const frameworkRoot = resolve(packageRoot, '.pbai4devs');
7
7
  export const packageInfo = JSON.parse(readFileSync(resolve(packageRoot, 'package.json'), 'utf8'));
8
- export const statePath = '.pbai4devs/estado/agentdevkit.json';
8
+ export const statePath = '.pbai4devs/state/agentdevkit.json';
9
+ export const legacyStatePath = '.pbai4devs/estado/agentdevkit.json';
9
10
  export const entryNames = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md'];
10
11
  export const begin = '<!-- BEGIN AGENTDEVKIT -->';
11
12
  export const end = '<!-- END AGENTDEVKIT -->';
package/src/i18n.mjs CHANGED
@@ -42,6 +42,21 @@ const messages = {
42
42
  };
43
43
  export const text = (language, key) => messages[language || 'pt'][key] || key;
44
44
  export function explainError(language, code) {
45
+ if (code === 'E_CONFIG_PARSE') return {
46
+ pt: 'Não foi possível analisar a configuração legada com segurança; revise o frontmatter e as aspas antes de executar update.',
47
+ en: 'The legacy configuration could not be safely parsed; review its frontmatter and quoted values before running update.',
48
+ es: 'No se pudo analizar la configuración anterior de forma segura; revise el frontmatter y las comillas antes de ejecutar update.',
49
+ }[language || 'pt'];
50
+ if (code === 'E_LEGACY_PATH') return {
51
+ pt: 'Ajuste os caminhos .pbai4devs/estado para .pbai4devs/state na configuração antes de executar update.',
52
+ en: 'Change .pbai4devs/estado paths to .pbai4devs/state in the configuration before running update.',
53
+ es: 'Cambie las rutas .pbai4devs/estado por .pbai4devs/state en la configuración antes de ejecutar update.',
54
+ }[language || 'pt'];
55
+ if (code === 'E_UPGRADE') return {
56
+ pt: 'Execute agentdevkit update antes de sincronizar ou alterar a configuração legada.',
57
+ en: 'Run agentdevkit update before syncing or changing the legacy configuration.',
58
+ es: 'Ejecute agentdevkit update antes de sincronizar o cambiar la configuración anterior.',
59
+ }[language || 'pt'];
45
60
  const value = {
46
61
  pt: { E_ARGS: 'Argumentos inválidos; consulte --help.', E_STATE: 'O estado do AgentDevKit está inválido.', E_SYMLINK: 'Um link simbólico impede a operação segura.', E_TARGET: 'Escolha uma pasta real e segura como destino.', E_PATH: 'Um caminho gerenciado é inválido.', E_BLOCK: 'Os marcadores do bloco gerenciado estão inválidos.', E_CHANGED: 'Um arquivo mudou depois do planejamento; execute novamente.', E_TEMPLATE: 'Um template necessário está inválido.' },
47
62
  en: { E_ARGS: 'Invalid arguments; see --help.', E_STATE: 'AgentDevKit state is invalid.', E_SYMLINK: 'A symbolic link prevents this operation.', E_TARGET: 'Choose a real, safe target directory.', E_PATH: 'A managed path is invalid.', E_BLOCK: 'Managed block markers are invalid.', E_CHANGED: 'A file changed after planning; try again.', E_TEMPLATE: 'A required template is invalid.' },
package/src/install.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { chmodSync, existsSync, lstatSync, readFileSync, writeFileSync, readdirSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, rmdirSync } from 'node:fs';
2
+ import { chmodSync, closeSync, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, writeFileSync, readdirSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, rmdirSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { synchronize, isReference } from '../.pbai4devs/scripts/sincronizar-agentes/SCRIPT.mjs';
@@ -8,7 +8,7 @@ import { nativePathBoundary } from '../.pbai4devs/scripts/lib/native-paths.mjs';
8
8
  import { canonicalEntrypoint, resolveEntrypoint, entrypointReference, renderEntrypointImports, extractManagedBlock, managedBlockDigest, mergeManagedContent, stripManagedContent } from '../.pbai4devs/scripts/lib/managed-content.mjs';
9
9
  import { extractTomlManagedBlock, tomlManagedBlockDigest, mergeTomlContent, stripTomlContent } from '../.pbai4devs/scripts/lib/managed-toml.mjs';
10
10
  import { writeAdapterManifest, adapterRoots, normalizeClients, resolveAdapters } from './adapters/index.mjs';
11
- import { packageRoot, packageInfo, statePath, entryNames, begin, end } from './config.mjs';
11
+ import { packageRoot, packageInfo, statePath, legacyStatePath, entryNames, begin, end } from './config.mjs';
12
12
  import { normalizeLanguage, text } from './i18n.mjs';
13
13
 
14
14
  const hash = value => createHash('sha256').update(value).digest('hex');
@@ -54,11 +54,11 @@ export function safePath(root, path) {
54
54
 
55
55
  function resourceAllowed(path, directory = false) {
56
56
  const parts = path.split('/');
57
- const folders = new Set(['agents', 'commands', 'external-skills', 'rules', 'scripts', 'skills', 'templates', 'tools', 'estado']);
57
+ const folders = new Set(['agents', 'commands', 'external-skills', 'rules', 'scripts', 'skills', 'templates', 'tools', 'state']);
58
58
  const files = new Set(['README.md', 'INSTRUCTIONS.md', 'COMPATIBILIDADE.md', 'LICENSE', '.gitignore']);
59
59
  if (!folders.has(parts[0]) && !(parts.length === 1 && files.has(parts[0]))) return false;
60
- if (parts[0] === 'estado') return directory && parts.length === 1 || path === 'estado/README.md';
61
- if (isGeneratedOutput(path, directory) || parts.some(part => ignored.has(part)) || parts[0] === 'adapters' || path === 'estado/agentdevkit.json' || path === '.npmignore') return false;
60
+ if (parts[0] === 'state') return directory && parts.length === 1 || path === 'state/README.md';
61
+ if (isGeneratedOutput(path, directory) || parts.some(part => ignored.has(part)) || parts[0] === 'adapters' || path === 'state/agentdevkit.json' || path === '.npmignore') return false;
62
62
  if (parts[0] === 'tools') return parts.length === 1 || (directory && parts.length === 2 && !['bin', 'npm-cache'].includes(parts[1])) || (parts.length === 2 && parts[1] === 'README.md') || (parts.length === 3 && ['TOOL.json', 'SCRIPT.mjs', 'README.md'].includes(parts[2]));
63
63
  if (parts[0] === 'external-skills') return parts.length === 1 || (parts.length === 2 && ['README.md', 'CATALOG.json'].includes(parts[1]));
64
64
  return true;
@@ -109,6 +109,7 @@ function read(root, path) {
109
109
  }
110
110
 
111
111
  function allowedManaged(path) {
112
+ if (path === '.pbai4devs/estado/README.md') return true;
112
113
  if (canonicalEntrypoint(path) || path === '.gitignore') return true;
113
114
  if (nativeMarkdown(path) || nativeToml(path)) return true;
114
115
  if (['catalog.json', 'skills.json', 'agents.json', 'rules.json', 'espelhos.conf'].some(name => path === `.pbai4devs/${name}`)) return true;
@@ -122,7 +123,7 @@ function nativeMarkdown(path) {
122
123
  && adapterRoots.some(root => {
123
124
  if (!path.startsWith(`${root}/`)) return false;
124
125
  const relative = path.slice(root.length + 1).split('/');
125
- return !['tools', 'scripts', 'templates', 'external-skills', 'estado', 'tests', 'docs', 'adapters', 'workflows'].includes(relative[0].toLowerCase())
126
+ return !['tools', 'scripts', 'templates', 'external-skills', 'estado', 'state', 'tests', 'docs', 'adapters', 'workflows'].includes(relative[0].toLowerCase())
126
127
  && !['readme.md', 'instructions.md'].includes(relative.at(-1).toLowerCase());
127
128
  });
128
129
  }
@@ -130,7 +131,7 @@ const nativeToml = path => path.startsWith('.gemini/commands/') && path.endsWith
130
131
  const nativeManagedText = path => nativeMarkdown(path) || nativeToml(path);
131
132
 
132
133
  export function loadState(root) {
133
- const content = read(root, statePath); if (content === null) return null;
134
+ const content = read(root, actualStatePath(root)); if (content === null) return null;
134
135
  let state; try { state = JSON.parse(content); } catch { fail('E_STATE', 'Invalid AgentDevKit state JSON.'); }
135
136
  if (state?.schemaVersion !== 1 || !normalizeLanguage(state.language) || typeof state.version !== 'string' || !state.files || typeof state.files !== 'object' || Array.isArray(state.files) || !state.blocks || typeof state.blocks !== 'object' || Array.isArray(state.blocks)) fail('E_STATE', 'Invalid AgentDevKit state.');
136
137
  if (state.clients !== undefined) {
@@ -144,6 +145,81 @@ export function loadState(root) {
144
145
  return state;
145
146
  }
146
147
 
148
+ function actualStatePath(root) {
149
+ const legacy = stat(safePath(root, '.pbai4devs/estado'));
150
+ const current = stat(safePath(root, '.pbai4devs/state'));
151
+ if (legacy && !legacy.isDirectory() || current && !current.isDirectory()) fail('E_STATE', 'AgentDevKit state must be a directory.');
152
+ if (legacy && current) fail('E_STATE', 'Both .pbai4devs/estado and .pbai4devs/state exist; preserve both and resolve the conflict.');
153
+ return legacy ? legacyStatePath : statePath;
154
+ }
155
+
156
+ function readLegacyConfiguration(root, path) {
157
+ const limit = 4 * 1024 * 1024, fd = openSync(safePath(root, path), 'r');
158
+ try {
159
+ if (!fstatSync(fd).isFile() || fstatSync(fd).size > limit) fail('E_STATE', 'Legacy configuration is too large or not a regular file.');
160
+ const buffer = Buffer.allocUnsafe(limit + 1);
161
+ let total = 0, count;
162
+ while (total < buffer.length && (count = readSync(fd, buffer, total, buffer.length - total, null)) > 0) total += count;
163
+ if (total > limit) fail('E_STATE', 'Legacy configuration is too large to inspect safely.');
164
+ return buffer.subarray(0, total);
165
+ } finally { closeSync(fd); }
166
+ }
167
+
168
+ function assertNoLegacyReferences(value) {
169
+ const legacy = /\.pbai4devs\/estado(?=$|\/|[\s"'\],}:#])/i;
170
+ const reject = () => fail('E_LEGACY_PATH', 'Replace .pbai4devs/estado references with .pbai4devs/state in the legacy configuration before running update.');
171
+ if (legacy.test(value)) reject();
172
+ const normalized = value.replaceAll('\r', '');
173
+ const header = normalized.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1];
174
+ if (header === undefined) {
175
+ if (normalized.startsWith('---')) fail('E_CONFIG_PARSE', 'Legacy configuration has an incomplete frontmatter block.');
176
+ return;
177
+ }
178
+ let documents = false;
179
+ for (const line of header.split('\n')) {
180
+ const top = line.match(/^([a-z_]+):\s*(.*)$/);
181
+ if (top) documents = top[1] === 'documentos';
182
+ const nested = !top && documents ? line.match(/^ ([a-z_]+):\s*(.*)$/) : null;
183
+ const raw = (top?.[2] ?? nested?.[2])?.trim();
184
+ if (!raw?.startsWith('"')) continue;
185
+ let decoded;
186
+ try { decoded = JSON.parse(raw); }
187
+ catch { fail('E_CONFIG_PARSE', 'Legacy configuration contains an ambiguous quoted scalar.'); }
188
+ if (typeof decoded !== 'string') fail('E_CONFIG_PARSE', 'Legacy configuration contains an invalid quoted scalar.');
189
+ if (legacy.test(decoded)) reject();
190
+ }
191
+ }
192
+
193
+ function legacyStateMigration(root) {
194
+ if (actualStatePath(root) !== legacyStatePath) return null;
195
+ const base = '.pbai4devs/estado', files = [], directories = [];
196
+ const visit = folder => {
197
+ const info = stat(safePath(root, folder));
198
+ if (!info?.isDirectory()) fail('E_STATE', `Invalid state directory: ${folder}`);
199
+ const names = readdirSync(safePath(root, folder)).sort();
200
+ directories.push({ path: folder, mode: info.mode & 0o777, names });
201
+ for (const name of names) {
202
+ const path = `${folder}/${name}`, item = stat(safePath(root, path));
203
+ if (item?.isDirectory()) visit(path);
204
+ else if (item?.isFile()) {
205
+ const configuration = path === `${base}/configuracao/ESTADO.md`;
206
+ const content = configuration ? readLegacyConfiguration(root, path) : read(root, path);
207
+ if (configuration) {
208
+ if (content.includes(0)) fail('E_STATE', 'Legacy configuration contains binary data.');
209
+ let value;
210
+ try { value = new TextDecoder('utf-8', { fatal: true }).decode(content); }
211
+ catch { fail('E_STATE', 'Legacy configuration is not valid UTF-8.'); }
212
+ assertNoLegacyReferences(value);
213
+ }
214
+ files.push({ path, target: path.replace(`${base}/`, '.pbai4devs/state/'), mode: item.mode & 0o777, content });
215
+ }
216
+ else fail('E_STATE', `Unsupported state entry: ${path}`);
217
+ }
218
+ };
219
+ visit(base);
220
+ return { files, directories };
221
+ }
222
+
147
223
  function extractBlock(content, first = begin, last = end) {
148
224
  const start = content.indexOf(first), finish = content.indexOf(last);
149
225
  if (start < 0 && finish < 0) return null;
@@ -194,7 +270,7 @@ function copyResources(source, destination) {
194
270
 
195
271
  function readDerivedState(target) {
196
272
  let entries = {}, outputs = {}, blocks = {}, files = {}, removedBlocks = [];
197
- const derived = read(target, '.pbai4devs/estado/derived.json');
273
+ const derived = read(target, actualStatePath(target).replace(/agentdevkit\.json$/, 'derived.json'));
198
274
  if (derived) {
199
275
  try {
200
276
  const value = JSON.parse(derived);
@@ -216,6 +292,10 @@ function readDerivedState(target) {
216
292
 
217
293
  export function planInstallation({ target, language = 'pt', mode = 'init', force = false, clients }) {
218
294
  const previous = loadState(target);
295
+ const migration = legacyStateMigration(target);
296
+ // A migration must update the installed scripts and pointers in the same
297
+ // transaction; a plain sync/agents/lang would leave old hard-coded paths.
298
+ if (migration && !['init', 'update'].includes(mode)) fail('E_UPGRADE', 'Run AgentDevKit update before migrating the legacy state directory.');
219
299
  if (mode !== 'init' && !previous) fail('E_MISSING', text(language, 'missing'));
220
300
  const selected = normalizeClients(clients ?? previous?.clients ?? ['all']);
221
301
  const active = resolveAdapters(selected);
@@ -272,7 +352,7 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
272
352
  bundled.push('LICENSE');
273
353
  }
274
354
  const supplied = new Set(bundled);
275
- const internal = new Set(['catalog.json', 'skills.json', 'agents.json', 'rules.json', 'espelhos.conf', '.gitignore', 'estado/README.md']);
355
+ const internal = new Set(['catalog.json', 'skills.json', 'agents.json', 'rules.json', 'espelhos.conf', '.gitignore', 'state/README.md', 'estado/README.md']);
276
356
  if (bundled.length) for (const path of Object.keys(previous?.files || {})) {
277
357
  if (path.startsWith('.pbai4devs/') && !supplied.has(path.slice(11)) && !internal.has(path.slice(11))) rmSync(safePath(stage, path), { force: true });
278
358
  }
@@ -302,10 +382,32 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
302
382
  }
303
383
  }
304
384
  if (!preserveNative('README.md') && !read(target, 'README.md')) write(stage, 'README.md', `---\ndescription: ${JSON.stringify(text(language, 'readme'))}\nlanguage: ${language}\n---\n\n# ${text(language, 'project')}\n\n${text(language, 'readme')}\n`);
305
- if (!existsSync(join(stage, '.pbai4devs/estado/README.md'))) write(stage, '.pbai4devs/estado/README.md', `---\ndescription: AgentDevKit state.\n---\n\n# AgentDevKit\n\n${text(language, 'state')}\n`);
385
+ if (!existsSync(join(stage, '.pbai4devs/state/README.md'))) write(stage, '.pbai4devs/state/README.md', `---\ndescription: AgentDevKit state.\n---\n\n# AgentDevKit\n\n${text(language, 'state')}\n`);
306
386
  const unknown = new Set(existing.filter(path => !supplied.has(path) && !previous?.files[`.pbai4devs/${path}`] && !internal.has(path)));
307
387
  const paths = walk(stage, '', path => !path.split('/').includes('.agent-tests')).filter(path => !path.startsWith('.pbai4devs/') || !unknown.has(path.slice(11)));
308
388
  const desired = new Map(paths.filter(path => !preserveNative(path)).map(path => [path, readFileSync(join(stage, path))]));
389
+ const migratedHuman = new Set();
390
+ for (const item of migration?.files || []) {
391
+ if (item.path === legacyStatePath) continue;
392
+ if (item.path === '.pbai4devs/estado/README.md') {
393
+ const managed = previous?.files?.[item.path] === hash(item.content);
394
+ const matchesTemplate = desired.get(item.target)?.equals(item.content);
395
+ desired.set(item.target, item.content);
396
+ if (!managed || !matchesTemplate) { recordPreserved(item.target, 'existing-file'); migratedHuman.add(item.target); }
397
+ continue;
398
+ }
399
+ if (desired.has(item.target)) fail('E_STATE', `State migration collides with a managed file: ${item.target}`);
400
+ desired.set(item.target, item.content);
401
+ migratedHuman.add(item.target);
402
+ }
403
+ // Preserve human README content; verified managed files may be updated.
404
+ const stateReadme = '.pbai4devs/state/README.md';
405
+ const currentStateReadme = read(target, stateReadme);
406
+ if (currentStateReadme && previous?.files?.[stateReadme] !== hash(currentStateReadme)) {
407
+ desired.set(stateReadme, currentStateReadme);
408
+ migratedHuman.add(stateReadme);
409
+ recordPreserved(stateReadme, 'existing-file');
410
+ }
309
411
  for (const [path, content] of desired) {
310
412
  if (!nativeManagedText(path) || canonicalEntrypoint(path)) continue;
311
413
  const current = read(target, path);
@@ -330,7 +432,7 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
330
432
  const manifest = { schemaVersion: 1, version: bundled.length ? packageInfo.version : previous.version, language, files: {}, blocks: {} };
331
433
  if (mode !== 'sync' || clients !== undefined || previous?.clients !== undefined) manifest.clients = selected;
332
434
  for (const [path, content] of desired) {
333
- if (path === 'README.md') continue;
435
+ if (path === 'README.md' || migratedHuman.has(path)) continue;
334
436
  const block = blockDigest(path, content);
335
437
  if (block) manifest.blocks[path] = block;
336
438
  else manifest.files[path] = hash(content);
@@ -348,10 +450,12 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
348
450
  const conflict = current && path !== statePath && !managed && !appendBlock;
349
451
  const changedBlock = current && knownBlocks[path] && !managed;
350
452
  if (conflict || changedBlock) conflicts.push(path);
351
- changes.push({ path, action: current ? 'update' : 'create', content, beforeHash: current ? hash(current) : null });
453
+ const migrated = migration?.files.find(item => item.target === path);
454
+ changes.push({ path, action: current ? 'update' : 'create', content, beforeHash: current ? hash(current) : null, ...(migrated ? { mode: migrated.mode } : {}) });
352
455
  }
353
456
  const wholeRecords = [previous?.files || {}, derivedEntries, derivedFiles];
354
457
  for (const path of new Set(wholeRecords.flatMap(record => Object.keys(record)))) if (!desired.has(path)) {
458
+ if (migration && path.startsWith('.pbai4devs/estado/')) continue;
355
459
  if (path === '.gitignore') { recordPreserved(path, 'project-owned'); continue; }
356
460
  if (aliasedEntrypoint(path)) continue;
357
461
  const current = read(target, path); if (!current) continue;
@@ -361,6 +465,7 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
361
465
  changes.push({ path, action: 'remove', content: null, beforeHash: hash(current) });
362
466
  }
363
467
  for (const [recordedPath, digest] of Object.entries(knownBlocks)) {
468
+ if (migration && recordedPath.startsWith('.pbai4devs/estado/')) continue;
364
469
  const path = canonicalEntrypoint(recordedPath) ? entryPaths.get(canonicalEntrypoint(recordedPath)) : recordedPath;
365
470
  if (desired.has(path)) continue;
366
471
  if (changes.some(change => change.path === path)) continue;
@@ -410,6 +515,7 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
410
515
  if (!known) conflicts.push(legacy);
411
516
  changes.push({ path: legacy, action: 'remove', content: null, beforeHash: hash(legacyContent) });
412
517
  }
518
+ for (const item of migration?.files || []) changes.push({ path: item.path, action: 'remove', content: null, beforeHash: hash(item.content) });
413
519
  const retiredRoots = adapterRoots.filter(root => !active.roots.includes(root) && changes.some(change => change.action === 'remove' && change.path.startsWith(`${root}/`) && (previous?.files[change.path] || previous?.blocks[change.path])));
414
520
  const ownedOutputs = [...new Set([...synchronized.ownedOutputs, ...ownedEntrypoints, statePath])].filter(path => !mixedPaths.has(path) && !overlapsPreserved(path));
415
521
  const hashes = {};
@@ -419,12 +525,13 @@ export function planInstallation({ target, language = 'pt', mode = 'init', force
419
525
  const current = read(target, path);
420
526
  if (current) { const source = current.toString('utf8'), block = extractBlock(source, '# BEGIN AGENT IGNORE', '# END AGENT IGNORE'); if (block && source.trim() === block.trim() && hash(block) === previous.blocks[path]) hashes[path] = hash(current); }
421
527
  }
422
- if (previous) hashes[statePath] = hash(read(target, statePath));
528
+ if (previous && !migration) hashes[statePath] = hash(read(target, statePath));
423
529
  const untrack = existsSync(target) ? planUntrack(target, hashes) : null;
530
+ if (migration && untrack?.paths.length) fail('E_STATE', 'State migration would change the Git index; preserve and resolve tracked outputs first.');
424
531
  const localIgnore = planLocalIgnore(target, { outputs: ownedOutputs, templateRoot: stage });
425
532
  const localIgnoreCheck = checkLocalIgnore(localIgnore, { replacedBlocks: replacedIgnoreBlocks(target, changes, previous) });
426
533
  conflicts.push(...(untrack?.conflicts || []), ...localIgnoreCheck.missing);
427
- return { target, language, mode, changes, conflicts: [...new Set(conflicts)].sort(), canApply: (!conflicts.length || force) && !untrack?.conflicts?.length && !localIgnoreCheck.missing.length, manifest, retiredRoots, ownedOutputs, untrack, localIgnore, localIgnoreCheck, preserved: [...preserved.values()].sort((a, b) => a.path.localeCompare(b.path)) };
534
+ return { target, language, mode, changes, conflicts: [...new Set(conflicts)].sort(), canApply: (!conflicts.length || force) && !untrack?.conflicts?.length && !localIgnoreCheck.missing.length, manifest, retiredRoots, ownedOutputs, untrack, localIgnore, localIgnoreCheck, migration, preserved: [...preserved.values()].sort((a, b) => a.path.localeCompare(b.path)) };
428
535
  } finally { rmSync(stage, { recursive: true, force: true }); }
429
536
  }
430
537
 
@@ -432,6 +539,17 @@ export function applyPlan(plan) {
432
539
  if (!plan.canApply) fail('E_CONFLICT', text(plan.language, 'conflict'));
433
540
  assertLocalIgnoreUnchanged(plan.localIgnore);
434
541
  const { target } = plan;
542
+ if (plan.migration) {
543
+ if (stat(safePath(target, '.pbai4devs/state'))) fail('E_CHANGED', 'State destination appeared after planning.');
544
+ for (const directory of plan.migration.directories) {
545
+ const info = stat(safePath(target, directory.path));
546
+ if (!info?.isDirectory() || (info.mode & 0o777) !== directory.mode || JSON.stringify(readdirSync(safePath(target, directory.path)).sort()) !== JSON.stringify(directory.names)) fail('E_CHANGED', `State directory changed after planning: ${directory.path}`);
547
+ }
548
+ for (const item of plan.migration.files) {
549
+ const info = stat(safePath(target, item.path));
550
+ if (!info?.isFile() || (info.mode & 0o777) !== item.mode || hash(readFileSync(safePath(target, item.path))) !== hash(item.content)) fail('E_CHANGED', `State file changed after planning: ${item.path}`);
551
+ }
552
+ }
435
553
  const backup = `.agent-tests/agentdevkit/backups/${Date.now()}-${randomUUID()}`;
436
554
  safePath(target, backup);
437
555
  for (const change of plan.changes) safePath(target, change.path);
@@ -457,10 +575,24 @@ export function applyPlan(plan) {
457
575
  const content = change.content;
458
576
  const signature = { path: change.path, hash: content === null ? null : hash(content) };
459
577
  if (content === null) { rmSync(file, { force: true }); applied.push(signature); }
460
- else atomicWrite(target, change.path, content, beforeModes.get(change.path), mode => {
578
+ else atomicWrite(target, change.path, content, beforeModes.get(change.path) ?? change.mode, mode => {
461
579
  signature.mode = mode; applied.push(signature);
462
580
  }, () => assertOriginal(change.path));
463
581
  }
582
+ if (plan.migration) {
583
+ for (const directory of plan.migration.directories) {
584
+ const destination = directory.path.replace(/^\.pbai4devs\/estado/, '.pbai4devs/state');
585
+ const file = safePath(target, destination), existing = stat(file);
586
+ if (existing && !existing.isDirectory()) fail('E_CHANGED', `Invalid state destination: ${destination}`);
587
+ if (!existing) mkdirSync(file, { recursive: true, mode: directory.mode });
588
+ chmodSync(file, directory.mode);
589
+ }
590
+ for (const directory of [...plan.migration.directories].sort((a, b) => b.path.length - a.path.length)) {
591
+ const file = safePath(target, directory.path), info = stat(file);
592
+ if (!info?.isDirectory() || readdirSync(file).length) fail('E_CHANGED', `State directory changed during migration: ${directory.path}`);
593
+ rmdirSync(file); removedDirectories.push({ path: directory.path, mode: directory.mode });
594
+ }
595
+ }
464
596
  pruneRemovedDirectories(plan, directory => removedDirectories.push(directory));
465
597
  const changesFallback = plan.changes.some(change => change.path === '.gitignore');
466
598
  // Metadata is committed last; its writer rolls back partial writes itself.
@@ -498,6 +630,11 @@ export function applyPlan(plan) {
498
630
  else rollbackErrors.push(failure);
499
631
  }
500
632
  }
633
+ if (plan.migration) for (const directory of [...plan.migration.directories].sort((a, b) => b.path.length - a.path.length)) {
634
+ const destination = directory.path.replace(/^\.pbai4devs\/estado/, '.pbai4devs/state');
635
+ try { const file = safePath(target, destination); if (stat(file)?.isDirectory() && !readdirSync(file).length) rmdirSync(file); }
636
+ catch (failure) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(failure.code)) rollbackErrors.push(failure); }
637
+ }
501
638
  if (preserved.length) {
502
639
  try { error.rollbackPreservedPaths = preserved; } catch { /* Preserve a exceção original. */ }
503
640
  }
File without changes