feat: add protocol compatibility diagnostics and historical readers

This commit is contained in:
2026-11-16 10:13:05 +00:00
parent a8a8faf5d8
commit f10c237d44
48 changed files with 1382 additions and 13 deletions
+34
View File
@@ -24,6 +24,40 @@ Use `ai-engineering` (or its installed alias `aie`). No server or model API is n
whole lists. Use DEC drafts for significant commitments; small work need not
invent a decision or plan merely to satisfy a ceremony.
## Compatibility and protocol updates
Run `aie project compatibility --format json` before considering an update. `status`
includes a compatibility summary and the diagnostic command. The diagnostic is
read-only: it inspects actual canonical files and record revisions, without locks,
backups, model calls or migrations. It includes AIE completion receipts, while ignored
runs, local backups and ordinary artifact payloads are excluded. Use `project validate`
for integrity.
`protocol.json` separates `schemaVersion` (the manifest shape) from `protocolVersion`
(the engineering contract revision). A missing `protocolVersion` denotes the legacy
baseline contract 1. The report exposes the installed CLI release, supported contract
versions, format catalog, observed versions and missing defaulted Work fields.
Storage `schemaVersion` and narrative `documentVersion` remain independent.
States are `CURRENT`, `LEGACY_COMPATIBLE`, `UNSUPPORTED` and `INVALID`. The first two
are readable, return exit 0 and do not require migration. Unsupported or invalid
records return exit 4 with file-specific diagnostics. A newer manifest does not prove
that old records were converted. A missing optional field is not by itself a defect.
Compatibility is separate from structural validation and completion readiness.
Keep historical and COMPLETED Works in their original formats. The CLI reads older
supported representations and applies documented defaults in memory, preserving
IDs, approvals, evidence, completion provenance and content hashes. Never reopen or
rewrite a completed Work merely to materialize current fields, topics or surveys.
`aie onboard` refreshes the entry instructions and manifest, with backups, while
leaving Works, evidence and revision history unchanged. A newer unsupported manifest
or contract is refused rather than overwritten; use a compatible CLI. No required
migration is registered in this release. Future conversions must have an explicit
public command, scope, preview, backups and repeatable execution. Do not invent a
migration or inspect AIE source code to discover consumer update procedures; report
public-interface gaps with evidence instead.
## Topics, surveys and refinement
Discussion remains the refinement space: receive ideas, organize topics, investigate,
+2 -1
View File
@@ -1,5 +1,6 @@
{
"schemaVersion": 1,
"protocolVersion": 1,
"protocol": "ai-engineering",
"entrypoint": "README.md",
"instructions": "AGENTS.md",
@@ -8,7 +9,7 @@
"command": "ai-engineering",
"aliases": ["aie"],
"startup": ["status --format json", "next-actions --format json", "work context <WRK> --format markdown"],
"capabilities": ["work", "discussion", "topics", "surveys", "answer-history", "proposal-dispositions", "fixture-adapters", "local-cli-adapters", "guided-agent-setup", "agent-doctor", "agent-routing", "run-provenance", "epic", "epic-policy-authorization", "epic-propagation", "epic-reconciliation", "decision-approval", "decision-history", "planning", "step-dependencies", "evidence", "completion", "plan-consolidation", "cancelled-scope-review", "work-reconciliation", "archive", "reopen"],
"capabilities": ["protocol-compatibility", "work", "discussion", "topics", "surveys", "answer-history", "proposal-dispositions", "fixture-adapters", "local-cli-adapters", "guided-agent-setup", "agent-doctor", "agent-routing", "run-provenance", "epic", "epic-policy-authorization", "epic-propagation", "epic-reconciliation", "decision-approval", "decision-history", "planning", "step-dependencies", "evidence", "completion", "plan-consolidation", "cancelled-scope-review", "work-reconciliation", "archive", "reopen"],
"humanApproval": "explicit-attestation",
"execution": "external-human-or-agent",
"legacyImport": false
+1 -1
View File
@@ -1,3 +1,3 @@
---
schemaVersion: 2
lastWork: "0002"
lastWork: "0003"
@@ -0,0 +1,11 @@
---
schemaVersion: 1
id: "ART-0001"
workId: "WRK-0003"
origin: "aie-compatibility-implementation.txt"
purpose: "Implementação e verificações preliminares do diagnóstico de compatibilidade"
path: "artifacts/evidence/ART-0001/payload"
sha256: "b009a496b049ae875075fd6ca250042b10a0d41448e9e80f0d03a49a3e72559a"
size: 1312
author: "agent"
createdAt: "2026-11-16T10:03:20.899471Z"
@@ -0,0 +1,11 @@
WRK-0003 — implementação de compatibilidade
Autorização: instrução explícita do usuário nesta sessão para criar a infraestrutura, sem migrar zelda-1 nem Works COMPLETED existentes.
Implementado: protocolVersion independente de schemaVersion; catálogo de formatos com versões de leitura/escrita; project compatibility e resumo em status; leitura dos arquivos correntes, revisões e recibos AIE; diagnóstico de campos opcionais legados; recusa de sobrescrever contratos futuros.
Verificado: ./gradlew test --tests '*CompatibilityTest' --console=plain passou com 8 testes antes de acrescentar o caso de recibos; testes OperationalSafetyTest, ProtocolIntegrationTest e ArchitectureTest também passaram. A regressão completa com o caso adicional de recibos está em execução.
CLI empacotada (JAR): project compatibility no AIE inspecionou 233 registros, incluindo 1 recibo; zelda-1 inspecionou 12 registros. Ambos retornaram LEGACY_COMPATIBLE, readable=true e migrationRequired=false, exit 0. Saídas completas temporárias: /tmp/aie-compatibility-project.json e /tmp/aie-compatibility-zelda.json.
Preservação: comparação SHA-256 de 302 arquivos em WRK-0001, WRK-0002 e .ai-engineering do zelda-1 confirmou igualdade byte a byte. Nenhum comando de migração foi executado nesses projetos.
@@ -0,0 +1,12 @@
---
schemaVersion: 1
id: "ART-0002"
workId: "WRK-0003"
origin: "aie-compatibility-final-verification.txt"
purpose: "Regressão, native smoke, diagnóstico real e preservação histórica da infraestrutura\
\ de compatibilidade"
path: "artifacts/evidence/ART-0002/payload"
sha256: "3867d205c335fbb53420d4a4634190dbba0b15e6521d9978e9ec098f14bdc4ab"
size: 6694
author: "agent"
createdAt: "2026-11-16T10:11:26.059225Z"
@@ -0,0 +1,53 @@
WRK-0003 — evidência final de compatibilidade
Escopo entregue: revisão do contrato independente do schema do manifesto, catálogo de versões de leitura/escrita, diagnóstico público project compatibility, resumo em status, inspeção de revisões e recibos de conclusão, bloqueio de contratos futuros, documentação pública e instalada, fixture histórica congelada.
Não há migração obrigatória registrada. Nenhuma migração ou reabertura dos Works COMPLETED existentes ou do piloto zelda-1 foi executada. Onboard atualizou somente .ai-engineering/README.md e protocol.json no AIE, com backups.
Verificação executada:
- ./gradlew test nativeCompile --console=plain: a etapa test passou (126 testes, 20 suites, zero falhas/erros/skips); a etapa nativeCompile falhou porque o JDK padrão não contém native-image.
- JAVA_HOME=/Users/niltonconstantino/.sdkman/candidates/java/25.5.5.0+3-graalce GRAALVM_HOME=/Users/niltonconstantino/.sdkman/candidates/java/25.5.5.0+3-graalce ./gradlew nativeCompile --console=plain: BUILD SUCCESSFUL.
- bash scripts/native-smoke.sh /Users/niltonconstantino/personal/workspace.personal/my-projects/ai-engineering/build/native/nativeCompile/ai-engineering: exit 0 fora do sandbox, incluindo novos cenários de compatibilidade, recusa de downgrade, preservação de legado e todos os cenários anteriores. A tentativa inicial dentro do sandbox parou por sysctl bloqueado.
- Native aie project compatibility no AIE após onboard: CURRENT, readable=true, migrationRequired=false.
- Native aie --project <zelda-1> project compatibility: LEGACY_COMPATIBLE, readable=true, migrationRequired=false.
- Native aie work context WRK-0001 e WRK-0002: COMPLETED, origens de conclusão HUMAN e SYSTEM_PLANS preservadas.
- Comparação SHA-256 de todos os 302 arquivos previamente capturados em WRK-0001, WRK-0002 e .ai-engineering do zelda-1: nenhuma diferença.
- aie project validate: valid=true, issues=[]. git diff --check: sem erros.
A fixture congelada valida leitura de formato antigo, aprovação histórica, evidência, hash de escopo e preservação byte a byte, incluindo após onboard. O diagnóstico diferencia compatibilidade de formato de integridade e prontidão para conclusão; versões desconhecidas não geram uma rota de conversão inventada.
As primeiras revisões do plano usaram defaults de autoria da CLI; DSC-0002 esclarece que os comandos foram executados pelo agente, sem aprovação humana de entrega. A autorização explícita de implementação consta em DSC-0001.
Hashes dos arquivos de implementação, documentação e testes:
1c5f0a918cfb7d8dc89bde1b48b56faf5a4ace62ea1601d3ba11918a8c517f4e .ai-engineering/README.md
5895627eff101f7073cf7aae128a2c621d3bc2351b5cedd703add7dda65f8aa4 .ai-engineering/protocol.json
0414345b72827bbb0a89bc1bc4bc5210204daeaeebb1806f8657d6424c45675a README.md
924a05809dacdc111137b30cf4bb1acacd389fa88740e2a8d1b08caa98343ecb docs/architecture.md
ecc2e98adcb1b2e4a2bee00bf9d80d4981b5b1fae21588f341f4d07cfbfa63cf docs/compatibility.md
cfc5d6df8d08632498deb2d6b7dd8834100aeb5394ce8d3c14cb069ceeed1434 docs/protocol.md
b81cf3da88ab73537770d5649f8b8213cbffbe1c1dbc275b0e899c16940c57ad scripts/native-smoke.sh
f3433769c0a1205f37fc827be8f9449674b6a8ef902db2d705530bbac23e5ecb src/main/java/net/intrepid/aiengineering/NativeHints.java
58f80360833bbbf780a6b3db250cbe4b85569fbf129a06723149608ad7288e55 src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java
eec862917985131f2f1da60395ab214faa117709d6ada29191977f73cc89b9c4 src/main/java/net/intrepid/aiengineering/filesystem/Documents.java
42dd90682874adc0a041ab6d8800a9fd850cafbd816e21bff96e999cf1f2f1f2 src/main/java/net/intrepid/aiengineering/filesystem/FormatVersions.java
494bd3d84c98a2533470bbeccfa1ba0ba1561d8a7b8be4d9a78132b9d0a4534a src/main/java/net/intrepid/aiengineering/filesystem/ProtocolException.java
ab31106f9355e44c370a3c0bdef44abc571c0a18ad65e1132c40e547c6207923 src/main/java/net/intrepid/aiengineering/project/ProtocolContract.java
5e6865eaeff6764796086c47fc19e248cf0256a7836869790db9c4ae11e896de src/main/java/net/intrepid/aiengineering/project/ProtocolGuide.java
e1f397714b9724f08169e896b31f0cd7226acbe07a1a8dd96e118173e29eb964 src/main/java/net/intrepid/aiengineering/verification/CompatibilityService.java
5655d1994c1deb48c858fb6d0d5ad9a9bdc5994e1ac123209323570680c0d8de src/main/java/net/intrepid/aiengineering/verification/VerificationService.java
1c5f0a918cfb7d8dc89bde1b48b56faf5a4ace62ea1601d3ba11918a8c517f4e src/main/resources/protocol/README.md
5895627eff101f7073cf7aae128a2c621d3bc2351b5cedd703add7dda65f8aa4 src/main/resources/protocol/protocol.json
85155d8a8e611fbe5a03638cb34747192b1d84179cb9facb53ad38b7e282eec4 src/test/java/net/intrepid/aiengineering/CompatibilityTest.java
bd83ae325eeccfbe49ee8d7453d773738592233f8d56e0595d66fc5e47724fa6 src/test/java/net/intrepid/aiengineering/ProtocolIntegrationTest.java
b5eab70fb460ad5f769828e84bb9f5c4a3a0da64423d4f779be80b5592bbb9be src/test/resources/compatibility/README.md
d9bdcf54dd002d7846a5f8fb214a93318258731838060b05f394e122d2c2677c src/test/resources/compatibility/baseline-v1/.ai-engineering/ai-engineering.yaml
a6090a1059dcc47e647bdf626edaae745250f6ceeebacfa4c8d47be3047f8ac9 src/test/resources/compatibility/baseline-v1/.ai-engineering/protocol.json
b9140d7534a25e61459751f2180416c398a3fcf11eadc4cce777018584ac4580 src/test/resources/compatibility/baseline-v1/.ai-engineering/works/.sequence.yaml
f7752c7e6568ef105d914564624ffb1f3382d1c066c8415377f400e2859177d1 src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/artifacts/evidence/ART-0001/artifact.yaml
98545564d0747210b91b933bf8554c4b7e36ba878e6662cb48156b08ff74e1ee src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/artifacts/evidence/ART-0001/payload
545dc8e36da222fdeaf9458f77880bf2d1842738b82bac5296cddf62452a7e01 src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/decisions/.history/DEC-0001/r0001.md
e3446e03b4a29f9c9b825806628663cfd1256c5063efcaddd6752a1ba50fed8e src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/decisions/DEC-0001.md
413a5c7eb3b5fbefb48c87fa178902b0fbd619b266100547cc9059441f26c38e src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/discussions/DSC-0001.md
9370531b72d488d2494b455483fe2a413473fde7ffa0f2e539b165e733c3ef27 src/test/resources/compatibility/baseline-v1/.ai-engineering/works/WRK-0001-delivered-baseline/work.md
Executável nativo SHA-256: 858507824ae8705e2c50bc06bcde838524392167d3d1ad6341e3eebb0c8ae167
@@ -0,0 +1,12 @@
---
schemaVersion: 1
id: "ART-0003"
workId: "WRK-0003"
origin: "ai-engineering:plans:26fd692ddba3509e88d031446d441a0849848d20b98b094c08f045c9c25f3027"
purpose: "Deterministic aggregation of completed Plans and reviewed cancellations;\
\ not semantic verification of prose criteria"
path: "artifacts/evidence/ART-0003/payload"
sha256: "26fd692ddba3509e88d031446d441a0849848d20b98b094c08f045c9c25f3027"
size: 283
author: "system:plans"
createdAt: "2026-11-16T10:11:35.942748Z"
@@ -0,0 +1,10 @@
{
"schemaVersion" : 1,
"workId" : "WRK-0003",
"inputHash" : "e48d3536a51a54b72c10790ad264ef2a0f50bddced889d4ed8851d71900eec8b",
"plans" : [ {
"id" : "PLN-0001",
"revision" : 8,
"sha256" : "e8097dd6e269a82a3993aba3151e1ccc5aee29e835e00271c45e2ea78f152644"
} ]
}
@@ -0,0 +1,13 @@
---
schemaVersion: 1
id: "DSC-0001"
workId: "WRK-0003"
discussionId: "main"
kind: "NOTE"
author: "agent"
createdAt: "2026-11-16T09:50:02.422633Z"
respondsTo: null
documentVersion: 2
---
Autorização explícita do usuário nesta sessão: criar a infraestrutura de compatibilidade mesmo sem migração necessária; zelda1 é piloto e não precisa ser migrado; Works COMPLETED existentes devem permanecer intactos e continuar legíveis e interpretáveis em versões posteriores. A execução limita-se ao AIE e a fixtures descartáveis. Esta autorização não atesta aprovação de entrega.
@@ -0,0 +1,13 @@
---
schemaVersion: 1
id: "DSC-0002"
workId: "WRK-0003"
discussionId: "main"
kind: "NOTE"
author: "agent"
createdAt: "2026-11-16T10:10:18.057321Z"
respondsTo: null
documentVersion: 2
---
Rastreabilidade de autoria: o agente criou o Plano e seus passos. author/updatedBy=human nas primeiras revisões resultou dos valores padrão da CLI, não de uma nova manifestação humana. A autorização explícita de implementação está registrada em DSC-0001; nenhuma aprovação humana de entrega foi atestada.
@@ -0,0 +1,19 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps: []
status: "OPEN"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 1
previousHash: null
updatedAt: "2026-11-16T09:50:02.714336Z"
updatedBy: "human"
changeReason: "Plan created"
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,30 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T09:50:03.355683Z"
status: "OPEN"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 2
previousHash: "f126c370a4b5e225ed8296563c3d2cfb19c313a3079b8ddec1e32196e446ed95"
updatedAt: "2026-11-16T09:50:03.355969Z"
updatedBy: "human"
changeReason: "Step added"
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,42 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T09:50:03.355683Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T09:50:04.057668Z"
status: "OPEN"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 3
previousHash: "9cc57268b41a4a8725f6a5f6df714c430b10dcd4d6d3dcca5c0298477fad7f60"
updatedAt: "2026-11-16T09:50:04.057691Z"
updatedBy: "human"
changeReason: "Step added"
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,42 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "ACTIVE"
result: "Implementação autorizada explicitamente pelo usuário."
evidence: []
updatedAt: "2026-11-16T09:50:04.828478Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T09:50:04.057668Z"
status: "ACTIVE"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 4
previousHash: "f864d25e997a60b9178bbd4e180b041f8d1c0a41f5efcb3a9338c17667fabc23"
updatedAt: "2026-11-16T09:50:04.828509Z"
updatedBy: "agent"
changeReason: "Implementação autorizada explicitamente pelo usuário."
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,45 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "COMPLETED"
result: "Contrato, catálogo, diagnóstico público e leitura de legado implementados;\
\ testes focados e inspeção dos dois projetos passaram."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T10:03:26.080558Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T09:50:04.057668Z"
status: "ACTIVE"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 5
previousHash: "4dbc5e8ce2fbc59aaa82f9cbddee547a76e3fd7abc809a47f3dfb1a3465d4fc4"
updatedAt: "2026-11-16T10:03:26.080586Z"
updatedBy: "agent"
changeReason: "Contrato, catálogo, diagnóstico público e leitura de legado implementados;\
\ testes focados e inspeção dos dois projetos passaram."
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,46 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "COMPLETED"
result: "Contrato, catálogo, diagnóstico público e leitura de legado implementados;\
\ testes focados e inspeção dos dois projetos passaram."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T10:03:26.080558Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "ACTIVE"
result: "Documentação e fixture histórica prontas; regressão completa e geração\
\ nativa em execução."
evidence: []
updatedAt: "2026-11-16T10:03:26.943708Z"
status: "ACTIVE"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 6
previousHash: "6344a8e0e775112994f729b5aef457e98a85b38fe36b1017e7e04140b1a7a525"
updatedAt: "2026-11-16T10:03:26.943733Z"
updatedBy: "agent"
changeReason: "Documentação e fixture histórica prontas; regressão completa e geraç\
ão nativa em execução."
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,49 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "COMPLETED"
result: "Contrato, catálogo, diagnóstico público e leitura de legado implementados;\
\ testes focados e inspeção dos dois projetos passaram."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T10:03:26.080558Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "COMPLETED"
result: "Documentação instalada e pública, fixture histórica, 126 testes e smoke\
\ nativo passaram; diagnóstico dos projetos reais e preservação de 302 arquivos\
\ históricos/piloto confirmados."
evidence:
- "ART-0002"
updatedAt: "2026-11-16T10:11:34.939996Z"
status: "ACTIVE"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 7
previousHash: "c5ac6782c1bf92ee43611201601865fa2f4e581e24ef552e603e7629337e287e"
updatedAt: "2026-11-16T10:11:34.940023Z"
updatedBy: "agent"
changeReason: "Documentação instalada e pública, fixture histórica, 126 testes e smoke\
\ nativo passaram; diagnóstico dos projetos reais e preservação de 302 arquivos\
\ históricos/piloto confirmados."
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,47 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-0003"
title: "Diagnóstico público e leitura histórica sem migração"
decisions: []
steps:
- id: "TSK-0001"
title: "Implementar contrato e diagnóstico de compatibilidade"
description: ""
acceptanceCriteria:
- "Comando público distingue contrato, formatos, legado legível e versões não suportadas\
\ sem escrita."
dependsOn: []
status: "COMPLETED"
result: "Contrato, catálogo, diagnóstico público e leitura de legado implementados;\
\ testes focados e inspeção dos dois projetos passaram."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T10:03:26.080558Z"
- id: "TSK-0002"
title: "Documentar e verificar continuidade histórica"
description: ""
acceptanceCriteria:
- "Testes e CLI empacotada preservam registros concluídos e documentam evolução;\
\ regressão passa."
dependsOn:
- "TSK-0001"
status: "COMPLETED"
result: "Documentação instalada e pública, fixture histórica, 126 testes e smoke\
\ nativo passaram; diagnóstico dos projetos reais e preservação de 302 arquivos\
\ históricos/piloto confirmados."
evidence:
- "ART-0002"
updatedAt: "2026-11-16T10:11:34.939996Z"
status: "COMPLETED"
author: "human"
createdAt: "2026-11-16T09:50:02.714336Z"
revision: 8
previousHash: "28bb6dc031ef79789ce15805ad1490855694d947998f7b6fcef4966bb25fcbb0"
updatedAt: "2026-11-16T10:11:35.345624Z"
updatedBy: "system:plans"
changeReason: "All required steps completed; reviewed cancellations retained"
documentVersion: 2
---
Adicionar contrato versionado e catálogo de formatos; expor diagnóstico somente leitura na CLI; documentar política de evolução; testar registros históricos e versões não suportadas, executar regressão e verificar preservação dos Works concluídos.
@@ -0,0 +1,80 @@
---
schemaVersion: 1
id: "WRK-0003"
title: "Infraestrutura de compatibilidade e evolução do protocolo"
description: ""
goal: "Diagnosticar versões e compatibilidade usando a CLI pública, preservando leitura\
\ e interpretação de registros históricos sem migração obrigatória."
motivation: ""
constraints:
- "Não migrar nem regravar os Works COMPLETED existentes ou o projeto piloto zelda-1."
acceptanceCriteria:
- "A CLI distingue contrato do protocolo e formatos persistidos, diagnosticando legado\
\ compatível e formatos não suportados sem escrever durante leituras."
- "Testes demonstram leitura e interpretação de Works históricos concluídos e preservaç\
ão byte a byte após diagnóstico e atualização das instruções."
- "Documentação instalada explica o diagnóstico e a evolução sem exigir acesso ao\
\ código-fonte."
status: "COMPLETED"
createdAt: "2026-11-16T09:48:15.430009Z"
updatedAt: "2026-11-16T10:11:35.978959Z"
author: "agent"
repositories:
- repositoryId: "ai-engineering"
path: "."
head: "bd2c9133dad87a90b95d108c141cfe9eacbe77a3"
dirty: false
discussions:
- "DSC-0001"
- "DSC-0002"
decisions: []
artifacts:
- "ART-0001"
- "ART-0002"
- "ART-0003"
plans:
- "PLN-0001"
completions:
- at: "2026-11-16T10:11:35.978959Z"
by: "system:plans"
summary: "All required Plans completed; requester=agent"
humanApproved: false
scopeHash: "3ba6a687117bed72317e065a3cea9cf53fa5c725fbca994e512ada0713e7f74f"
criteria:
- criterion: 1
text: "A CLI distingue contrato do protocolo e formatos persistidos, diagnosticando\
\ legado compatível e formatos não suportados sem escrever durante leituras."
evidence:
- "ART-0003"
- criterion: 2
text: "Testes demonstram leitura e interpretação de Works históricos concluídos\
\ e preservação byte a byte após diagnóstico e atualização das instruções."
evidence:
- "ART-0003"
- criterion: 3
text: "Documentação instalada explica o diagnóstico e a evolução sem exigir acesso\
\ ao código-fonte."
evidence:
- "ART-0003"
integrations: []
noIntegrationReason: "Canonical changes and execution results are recorded in the\
\ Plan step evidence"
origin: "SYSTEM_PLANS"
delegation: null
aggregation:
receipt: "ART-0003"
inputHash: "e48d3536a51a54b72c10790ad264ef2a0f50bddced889d4ed8851d71900eec8b"
requester: "agent"
requestId: "0f38bb1b-3484-4d10-a8af-1dac0b43564e"
events:
- action: "COMPLETE"
by: "system:plans"
reason: "All required Plans completed; requester=agent"
at: "2026-11-16T10:11:35.978959Z"
archived: false
topics: []
surveys: []
dispositions: []
agentRuns: []
epic: false
---
+19
View File
@@ -126,6 +126,25 @@ The root instructions point agents to that entry. Automatic discovery still depe
on the agent inspecting project instructions; a CLI cannot force an arbitrary model
to inspect hidden folders or obey a protocol. Exported context includes the guide.
## Inspect compatibility before updating
```sh
aie project compatibility --format json
```
`status` includes a compatibility summary. The diagnostic separates the installed
CLI release, protocol contract revision and actual storage formats, including record
history. `CURRENT` and `LEGACY_COMPATIBLE` both mean readable; neither requires a
migration. `UNSUPPORTED` and `INVALID` return exit 4 and identify affected files.
Validation of references and evidence remains `aie project validate`.
Keep completed Works in their existing formats. Older supported files are interpreted
in memory; reads and diagnostics never normalize them on disk. `aie onboard` updates
only entry instructions and the manifest, with backups. It refuses to overwrite a
newer unsupported contract. There is no required data migration in this release.
See [compatibility and evolution](docs/compatibility.md) for the version policy and
the contract for future migrations; no source-code inspection is needed by consumers.
## Discuss topics and answer surveys
Ideas remain Discussion entries, organized by Work-local topics. Existing discussion
+15
View File
@@ -216,6 +216,21 @@ receipts from their input key, allowing reuse after interrupted publication.
Reconciliation derives state from files; no mutable in-memory index is authoritative.
Details and explicit reopening/reauthorization rules are in [epics.md](epics.md).
## Compatibility inspection
The project module owns the protocol contract revision independently of the CLI
release and manifest schema. Filesystem owns the supported storage-format catalog;
existing typed readers continue interpreting older representations in memory.
Verification's compatibility service inspects actual metadata and typed content,
including record revisions and system completion receipts. The CLI exposes a full
read-only report through `project compatibility` and a summary in `status`.
This adds no automatic conversion or blanket normalization. Onboarding refreshes
entry instructions with backups and refuses to overwrite an unsupported contract.
Frozen prior-release fixtures protect historical approvals, completion provenance,
scope hashes and bytes. See [compatibility](compatibility.md) for the public contract
and requirements before a future incompatible writer or migration is introduced.
## Earlier framework review and migration
Both implementations were inspected read-only:
+102
View File
@@ -0,0 +1,102 @@
# Compatibility and protocol evolution
A project's historical records do not have to be rewritten whenever AIE evolves.
Completed Works retain their original files, approvals, evidence and completion
provenance. Continued readability is a reader responsibility, not a reason to reopen
delivered work or to add current refinement content to old Works.
## Public inspection
Run `aie project compatibility --format json` using the installed executable.
It reports:
- `cliVersion`: the executable release, separately from data compatibility.
- `currentProtocolVersion` and `readableProtocolVersions`: supported contract revisions.
- `formats`: supported read versions and the current write version for each format family.
- `findings`: observed versions, missing defaulted fields and diagnostics by file.
- `state`, `readable`, `migrationRequired` and public guidance.
The scan covers configuration, discovery manifest, Work counter, all Works (including
archived and completed), canonical record documents, artifact manifests, AIE-generated
completion receipts and record revision files. It does not treat local backups,
ignored runs or ordinary artifact payloads as protocol records. It checks missing
references to current records. It does not
validate revision links, evidence integrity, semantic acceptance criteria or delivery
readiness; run `project validate` and `work check` for their respective contracts.
No repository commands, adapters, locks or writes occur during compatibility reads.
| State | Meaning | CLI exit |
|---|---|---|
| `CURRENT` | Observed representations match current supported formats | 0 |
| `LEGACY_COMPATIBLE` | Supported older representations or omitted defaulted Work fields | 0 |
| `UNSUPPORTED` | A declared version has no supported reader | 4 |
| `INVALID` | Malformed metadata, unknown fields, missing records or invalid typed content | 4 |
The report is an inspection, not a conversion plan. No required migrations are
registered, so `migrationRequired` is false, including for unsupported versions:
an unknown version is not evidence that an older CLI can convert it. Unsupported
records require a CLI with the appropriate reader; invalid data needs deliberate
repair. Basic command/path errors retain the usual exit codes.
## Three independent version dimensions
`protocol.json.schemaVersion` describes the manifest's structure. Its new optional
`protocolVersion` identifies the engineering contract. The initial explicit contract
revision is 1; absent `protocolVersion` means the pre-versioned baseline contract 1
and is reported as legacy compatible. The CLI release number is not a substitute
for either. Unsupported declared manifest/contract versions prevent ordinary CLI
operations and onboarding from overwriting a newer contract. Compatibility inspection
remains available to explain the mismatch.
The format catalog is deliberately small:
| Format | Current writer | Supported readers |
|---|---|---|
| Manifest schema | 1 | 1 |
| Canonical record schema (including configuration and Work) | 1 | 1 |
| Narrative document | 2 | 1, 2 |
| Metadata-only document (Work) | 1 | 1 |
| Work sequence | 2 | 1, 2 |
`schemaVersion` and `documentVersion` describe different layers of one file. A
discussion may have record schema 1 in document version 2. An omitted document
version means 1. Work operational/refinement/EPIC fields absent from earlier schema 1
records retain their documented empty/false defaults. Existing sequence readers
interpret legacy decimal reservations without changing identifier spelling; only an
explicit creation of a new Work advances and writes the sequence.
The installed manifest declares the expected contract, not a certificate that every
record has been converted. The scanner reads actual versions in current records and
history; mixed supported versions are normal. Capabilities are discovery labels,
not independent migration versions or evidence that a feature has been configured.
## Updating instructions and future migrations
`aie onboard` is idempotent and backs up changed entry files. It refreshes the README,
agent instructions and manifest, preserving project rules outside the managed block.
It does not convert Works, decisions, history, evidence or the Work counter, and does
not manufacture topics, answers, decisions or approval. A historical Work remains
legacy compatible after onboarding, which is expected. Use only the installed CLI
and public documentation for consumer operations; report gaps rather than reading the
implementation to infer a procedure.
When introducing an incompatible format or contract, add an explicit supported
reader/adaptation path and retained fixtures. Unknown schemas and fields must not
be silently ignored to simulate compatibility. Increasing a writer version must not
remove an existing reader or alter the meaning of historical approval/provenance.
A future required conversion must declare its source and target versions and expose
a public command that previews exact scope before applying changes, backs up original
bytes, resumes safely and is idempotent. The report may only claim a required migration
when a known route actually exists. Completed historical Works must retain a read path;
they must not be selected for blanket normalization. There is no placeholder migration
command and no automatic project-wide rewrite in this release.
## Historical regression fixture
`CompatibilityTest` loads a frozen project produced by the prior 0.1.0 native
executable, with a pre-versioned manifest, legacy sequence, omitted Work fields,
YAML-only discussion and decision revision, accepted decision, evidence and completed
Work. The tests compare all stored bytes before/after reads, and all Work files
before/after onboarding. They also check interpreted approval/completion provenance,
the original scope digest, mixed versions and unsupported/corrupt formats.
+12
View File
@@ -471,6 +471,18 @@ described in discussion/reference files, rather than copied into this workspace.
`artifacts/outputs` is versionable for deliberately retained outputs; use ignored `runs/`
for large temporary results. No command creates large output files by default.
## Compatibility and evolution
`project compatibility` inspects actual stored formats and revisions without writes.
`protocol.json.schemaVersion` versions the manifest, while optional `protocolVersion`
versions the engineering contract (absent means the supported legacy baseline 1).
The diagnostic exposes the supported read/write format catalog separately from the
executable release. Old compatible records remain valid and readable without
normalization, including COMPLETED Works. `onboard` updates only entry instructions
and the manifest; a newer unsupported contract is never silently overwritten.
See [compatibility and evolution](compatibility.md) for public states, update guidance
and requirements for future explicit conversions. No required migration exists today.
## Context and continuity
`work context --format markdown|json` loads only canonical project/Work files. It
+27
View File
@@ -27,6 +27,28 @@ cd plain
printf 'Existing source\n' > main.txt
aie_without_git init --name 'Simple Project' > init.yaml
aie_without_git work create 'Continue application' --goal 'Preserve local context' > work.yaml
aie_without_git project compatibility --format json > compatibility.json
grep -q '"state" : "CURRENT"' compatibility.json
grep -q '"migrationRequired" : false' compatibility.json
grep -q '"protocolVersion": 1' .ai-engineering/protocol.json
cp .ai-engineering/protocol.json baseline-protocol.json
sed 's/"protocolVersion": 1/"protocolVersion": 99/' baseline-protocol.json > .ai-engineering/protocol.json
cp .ai-engineering/protocol.json future-protocol.json
if aie_without_git project compatibility --format json > future-compatibility.json; then
echo 'Unsupported contract unexpectedly succeeded' >&2
exit 1
else
test "$?" -eq 4
fi
grep -q '"state" : "UNSUPPORTED"' future-compatibility.json
if aie_without_git onboard > refused-onboard.txt 2>&1; then
echo 'A newer contract was silently overwritten' >&2
exit 1
else
test "$?" -eq 4
fi
cmp future-protocol.json .ai-engineering/protocol.json
cp baseline-protocol.json .ai-engineering/protocol.json
printf '%s' 'No repository is required' > proposal.md
aie_without_git discussion add WRK-0001 --text-file proposal.md > discussion.md
aie_without_git artifact add WRK-0001 --file main.txt --purpose 'Initial source evidence' > artifact.yaml
@@ -49,6 +71,11 @@ awk '
{ print }
' "$aie_discussion" > legacy.md
cp legacy.md "$aie_discussion"
cp "$aie_discussion" before-compatibility.md
aie_without_git project compatibility --format json > legacy-compatibility.json
grep -q '"state" : "LEGACY_COMPATIBLE"' legacy-compatibility.json
grep -q '"readable" : true' legacy-compatibility.json
cmp before-compatibility.md "$aie_discussion"
aie_without_git work context WRK-0001 --format json > before.json
aie_without_git discussion migrate WRK-0001 --format json > migration.json
grep -q '"converted" : 1' migration.json
@@ -1,6 +1,7 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.filesystem.FormatVersions;
import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.*;
@@ -21,7 +22,9 @@ public final class NativeHints implements RuntimeHintsRegistrar {
Work.Delegation.class, Epic.class, Epic.Link.class, Epic.Authorization.class,
EpicCoordinator.Child.class, EpicCoordinator.Evaluation.class, EpicCoordinator.ChildReceipt.class, EpicCoordinator.Receipt.class,
EpicCoordinator.Transition.class, EpicCoordinator.Propagation.class, EpicCoordinator.LifecycleResult.class,
ProtocolGuide.Report.class, ProtocolGuide.Manifest.class, VerificationService.Action.class, VerificationService.WorkSummary.class, VerificationService.ProjectStatus.class,
ProtocolGuide.Report.class, ProtocolGuide.Manifest.class, FormatVersions.Format.class,
CompatibilityService.Report.class, CompatibilityService.Finding.class, CompatibilityService.Summary.class,
VerificationService.Action.class, VerificationService.WorkSummary.class, VerificationService.ProjectStatus.class,
Topic.class, TopicService.View.class, Survey.class, Survey.Question.class, Survey.Option.class, Survey.Answer.class,
Disposition.class, ProjectConfig.Executor.class, ProjectConfig.Agents.class, AgentContext.class, AgentAdapter.Request.class,
AgentProposal.class, AgentProposal.TopicDraft.class, AgentProposal.SurveyDraft.class, AgentProposal.QuestionDraft.class,
@@ -17,7 +17,7 @@ import java.nio.file.Files;
import java.util.List;
@Command(name = "ai-engineering", description = "Portable engineering protocol for humans and AI agents.",
mixinStandardHelpOptions = true, version = "ai-engineering 0.1.0")
mixinStandardHelpOptions = true, version = "ai-engineering " + ProtocolContract.CLI_VERSION)
public final class EngineeringCli implements Runnable {
private final Path cwd;
private final ProjectService projects = new ProjectService();
@@ -55,7 +55,10 @@ public final class EngineeringCli implements Runnable {
command.getSubcommands().values().forEach(child -> configure(child, out, err));
}
@Override public void run() { commandLine.usage(output); }
private Path root() { return projects.discover(cwd, project == null ? null : resolve(project)); }
private Path discoveredRoot() { return projects.discover(cwd, project == null ? null : resolve(project)); }
private Path root() {
Path root = discoveredRoot(); ProtocolGuide.requireSupportedVersion(root); return root;
}
private Path resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); }
enum Format { markdown, json }
private int emit(Object value, Format format) {
@@ -123,6 +126,12 @@ public final class EngineeringCli implements Runnable {
@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(verification.nextActions(root(), id), format); }
@Command(name = "project", mixinStandardHelpOptions = true, description = "Inspect and validate the engineering project.")
public class ProjectCommands {
@Command(name = "compatibility", mixinStandardHelpOptions = true,
description = "Inspect contract and stored formats without writing or migrating historical Works.")
int compatibility(@Option(names = "--format", defaultValue = "markdown") Format format) {
var result = new CompatibilityService().inspect(discoveredRoot());
emit(result, format); return result.readable() ? 0 : 4;
}
@Command(name = "show", mixinStandardHelpOptions = true)
int show(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()), format); }
@Command(name = "validate", mixinStandardHelpOptions = true)
@@ -55,11 +55,12 @@ public final class Documents {
catch (RuntimeException e) { throw ProtocolException.validation("Invalid " + type.getSimpleName() + " at " + path + ": " + e.getMessage()); }
}
public static int documentVersion(Path path) { return version(parts(path).metadata(), path); }
/** Raw persisted metadata for read-only diagnostics, without materializing defaults. */
public static ObjectNode metadata(Path path) { return parts(path).metadata(); }
private static int version(ObjectNode metadata, Path path) {
var value = metadata.get("documentVersion");
if (value == null) return 1;
if (value.isIntegralNumber() && (value.bigIntegerValue().equals(java.math.BigInteger.ONE)
|| value.bigIntegerValue().equals(java.math.BigInteger.TWO))) return value.intValue();
if (value.isIntegralNumber() && value.canConvertToInt() && FormatVersions.DOCUMENT.supports(value.intValue())) return value.intValue();
throw ProtocolException.validation("Unsupported documentVersion at " + path + ": " + value);
}
private record Parts(ObjectNode metadata, String body) {}
@@ -0,0 +1,18 @@
package net.intrepid.aiengineering.filesystem;
import java.util.List;
/** Supported storage formats, independent of executable and protocol contract versions. */
public final class FormatVersions {
private FormatVersions() {}
public record Format(String id, int currentWriteVersion, List<Integer> readableVersions) {
public Format { readableVersions = List.copyOf(readableVersions); }
public boolean supports(int version) { return readableVersions.contains(version); }
}
public static final Format SCHEMA = new Format("record-schema", 1, List.of(1));
public static final Format MANIFEST = new Format("manifest-schema", 1, List.of(1));
public static final Format DOCUMENT = new Format("narrative-document", 2, List.of(1, 2));
public static final Format METADATA = new Format("metadata-document", 1, List.of(1));
public static final Format SEQUENCE = new Format("work-sequence", 2, List.of(1, 2));
public static List<Format> supported() { return List.of(MANIFEST, SCHEMA, DOCUMENT, METADATA, SEQUENCE); }
}
@@ -12,6 +12,6 @@ public final class ProtocolException extends RuntimeException {
return value;
}
public static void schema(int version) {
if (version != 1) throw validation("Unsupported or missing schemaVersion: " + version);
if (!FormatVersions.SCHEMA.supports(version)) throw validation("Unsupported or missing schemaVersion: " + version);
}
}
@@ -0,0 +1,18 @@
package net.intrepid.aiengineering.project;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.util.List;
/** A contract revision is not a storage schema or a product release number. */
public final class ProtocolContract {
private ProtocolContract() {}
public static final String CLI_VERSION = "0.1.0";
public static final int CURRENT = 1;
public static final List<Integer> READABLE = List.of(1);
/** Pre-versioned manifests describe the supported baseline contract, without rewriting them. */
public static int effective(Integer declared) { return declared == null ? 1 : declared; }
public static void require(Integer declared) {
if (!READABLE.contains(effective(declared))) throw ProtocolException.validation(
"Unsupported protocolVersion: " + declared + "; use a compatible CLI; inspect with aie project compatibility");
}
}
@@ -38,9 +38,11 @@ public final class ProtocolGuide {
}
public record Manifest(int schemaVersion, String protocol, String entrypoint, String instructions, String configuration,
String works, String command, List<String> aliases, List<String> startup, List<String> capabilities,
String humanApproval, String execution, boolean legacyImport) {
String humanApproval, String execution, boolean legacyImport,
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) Integer protocolVersion) {
public Manifest {
ProtocolException.schema(schemaVersion);
ProtocolContract.require(protocolVersion);
if (!"ai-engineering".equals(protocol) || !"ai-engineering".equals(command)
|| !"README.md".equals(entrypoint) || !"AGENTS.md".equals(instructions)
|| !"ai-engineering.yaml".equals(configuration) || !"works".equals(works)
@@ -60,6 +62,7 @@ public final class ProtocolGuide {
Path file = Filespace.resolve(workspace, name);
if (!Files.isRegularFile(file) || Filespace.read(file).isBlank()) throw ProtocolException.validation("Incomplete protocol entry contract: " + name + "; run onboard");
}
requireSupportedVersion(root);
var manifest = Documents.readJson(Filespace.resolve(workspace, "protocol.json"), Manifest.class);
for (String relative : List.of(manifest.entrypoint(), manifest.instructions(), manifest.configuration()))
if (!Files.isRegularFile(Filespace.resolve(workspace, relative))) throw ProtocolException.validation("Missing manifest entry: " + relative);
@@ -69,6 +72,21 @@ public final class ProtocolGuide {
public Report { updated = List.copyOf(updated); backups = List.copyOf(backups); }
}
public static void preflight(Path root) { rootInstructions(root); }
/** Refuse to overwrite a newer contract, even when only refreshing instructions. */
public static void requireSupportedVersion(Path root) {
Path path = Filespace.resolve(root, ".ai-engineering/protocol.json");
if (!Files.exists(path)) return;
tools.jackson.databind.node.ObjectNode metadata;
try { metadata = Documents.readJson(path, tools.jackson.databind.node.ObjectNode.class); }
catch (ProtocolException e) { return; } // onboard can repair malformed entry files.
if (metadata == null) return;
for (String field : List.of("schemaVersion", "protocolVersion")) {
var value = metadata.get(field);
if (value != null && (!value.isIntegralNumber() || !value.canConvertToInt()
|| !(field.equals("schemaVersion") ? FormatVersions.MANIFEST.readableVersions() : ProtocolContract.READABLE).contains(value.intValue())))
throw ProtocolException.validation("Unsupported " + field + ": " + value + "; use a compatible CLI; inspect with aie project compatibility");
}
}
private static String rootInstructions(Path root) {
Path path = Filespace.resolve(root, "AGENTS.md");
if (!Files.exists(path)) return POINTER + "\n";
@@ -80,7 +98,9 @@ public final class ProtocolGuide {
return original + (original.isEmpty() ? "" : original.endsWith("\n") ? "\n" : "\n\n") + POINTER + "\n";
}
public static Report install(Path root) {
requireSupportedVersion(root);
return Filespace.locked(root, () -> {
requireSupportedVersion(root);
var content = new LinkedHashMap<String, String>();
for (String name : List.of("README.md", "AGENTS.md", "protocol.json")) content.put(".ai-engineering/" + name, bundled(name));
content.put("AGENTS.md", rootInstructions(root));
@@ -0,0 +1,170 @@
package net.intrepid.aiengineering.verification;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.Decision;
import net.intrepid.aiengineering.planning.Plan;
import net.intrepid.aiengineering.artifact.Artifact;
import net.intrepid.aiengineering.agent.AgentRun;
import tools.jackson.databind.node.ObjectNode;
import java.nio.file.*;
import java.util.*;
/** Format inspection only. Does not lock, write, migrate, reopen or reinterpret historical approvals. */
public final class CompatibilityService {
public enum State { CURRENT, LEGACY_COMPATIBLE, UNSUPPORTED, INVALID }
public record Summary(State state, boolean readable, boolean migrationRequired, String command) {}
public record Finding(String path, String recordType, State state, Map<String, String> versions,
List<String> missingFields, String message) {
public Finding { versions = Collections.unmodifiableMap(new LinkedHashMap<>(versions)); missingFields = List.copyOf(missingFields); }
}
public record Report(int schemaVersion, String cliVersion, int currentProtocolVersion,
List<Integer> readableProtocolVersions, List<FormatVersions.Format> formats, State state,
boolean readable, boolean migrationRequired, List<Finding> findings, List<String> guidance) {
public Report {
readableProtocolVersions = List.copyOf(readableProtocolVersions); formats = List.copyOf(formats);
findings = List.copyOf(findings); guidance = List.copyOf(guidance);
}
public Summary summary() { return new Summary(state, readable, migrationRequired, "aie project compatibility --format json"); }
}
private record RecordType(String area, Class<?> type, String bodyField) {}
private static final List<RecordType> RECORDS = List.of(
new RecordType("discussions", DiscussionEntry.class, "text"), new RecordType("decisions", Decision.class, "text"),
new RecordType("plans", Plan.class, "description"), new RecordType("topics", Topic.class, "description"),
new RecordType("surveys", Survey.class, "description"), new RecordType("dispositions", Disposition.class, "reason"),
new RecordType("agent-runs", AgentRun.class, "task"), new RecordType("epic", Epic.class, "reason"));
private static final List<String> WORK_DEFAULTS = List.of("plans", "completions", "events", "archived",
"topics", "surveys", "dispositions", "agentRuns", "epic");
public Report inspect(Path root) {
var findings = new ArrayList<Finding>();
inspect(root, ".ai-engineering/ai-engineering.yaml", "project", ProjectConfig.class, null, false, findings);
Path manifest = Filespace.resolve(root, ".ai-engineering/protocol.json");
if (Files.exists(manifest)) inspect(root, ".ai-engineering/protocol.json", "manifest", ProtocolGuide.Manifest.class, null, false, findings);
else findings.add(new Finding(".ai-engineering/protocol.json", "manifest", State.LEGACY_COMPATIBLE, Map.of(), List.of(),
"No discovery manifest. Existing records are inspected independently; onboard can install the entry instructions."));
if (findings.stream().noneMatch(f -> f.recordType().equals("manifest") && (f.state() == State.UNSUPPORTED || f.state() == State.INVALID))) {
try { ProtocolGuide.validate(root); }
catch (RuntimeException e) { invalid(findings, ".ai-engineering/protocol.json", "entry-contract", e.getMessage()); }
}
Path workspace = Filespace.resolve(root, ".ai-engineering/works");
Path sequence = Filespace.resolve(root, ".ai-engineering/works/.sequence.yaml");
if (Files.exists(sequence)) inspect(root, root.relativize(sequence).toString(), "sequence", WorkService.Sequence.class, null, false, findings);
visit(root, workspace, findings, folder -> {
Path workFile = folder.resolve("work.md");
inspect(root, relative(root, workFile), "work", Work.class, null, true, findings);
if (!Files.exists(sequence)) invalid(findings, relative(root, sequence), "sequence", "Missing Work sequence");
for (var record : RECORDS) {
Path area = Filespace.resolve(root, relative(root, folder.resolve(record.area())));
if (!Files.exists(area)) continue;
visit(root, area, findings, file -> inspectRecord(root, file, record, findings));
Path history = Filespace.resolve(root, relative(root, area.resolve(".history")));
if (Files.exists(history)) visit(root, history, findings,
revisions -> visit(root, revisions, findings, file -> inspectRecord(root, file, record, findings)));
}
Path evidence = Filespace.resolve(root, relative(root, folder.resolve("artifacts/evidence")));
if (Files.exists(evidence)) visit(root, evidence, findings, artifact -> {
Path manifestPath = artifact.resolve("artifact.yaml");
inspect(root, relative(root, manifestPath), "artifact", Artifact.class, null, false, findings);
if (findings.getLast().state() == State.INVALID || findings.getLast().state() == State.UNSUPPORTED) return;
var record = Documents.read(manifestPath, Artifact.class);
Class<?> receipt = record.origin().startsWith(PlanCoordinator.RECEIPT_ORIGIN) ? PlanCoordinator.Receipt.class
: record.origin().startsWith(EpicCoordinator.RECEIPT_ORIGIN) ? EpicCoordinator.Receipt.class : null;
if (receipt != null) inspect(root, relative(root, Filespace.resolve(folder, record.path())), "completion-receipt", receipt, null, false, findings);
});
// Missing referenced records are not evidence of a readable historical format.
try {
Work work = Documents.readDocument(workFile, Work.class);
var references = new LinkedHashMap<String, List<String>>();
references.put("discussions", work.discussions()); references.put("decisions", work.decisions());
references.put("plans", work.plans()); references.put("topics", work.topics()); references.put("surveys", work.surveys());
references.put("dispositions", work.dispositions()); references.put("agent-runs", work.agentRuns());
references.put("epic", work.epic() ? List.of(work.id()) : List.of());
references.forEach((area, ids) -> ids.forEach(id -> {
String path = relative(root, folder.resolve(area).resolve(id + ".md"));
if (!Files.isRegularFile(Filespace.resolve(root, path))) invalid(findings, path, area, "Missing referenced record");
}));
for (String id : work.artifacts()) {
String path = relative(root, folder.resolve("artifacts/evidence/" + id + "/artifact.yaml"));
if (!Files.isRegularFile(Filespace.resolve(root, path))) invalid(findings, path, "artifact", "Missing referenced artifact manifest");
}
} catch (RuntimeException ignored) { /* The Work's parse diagnostic was already recorded above. */ }
});
// Presence/version inspection is independent from structural/evidence validation.
State state = findings.stream().map(Finding::state).max(Comparator.naturalOrder()).orElse(State.CURRENT);
boolean readable = state == State.CURRENT || state == State.LEGACY_COMPATIBLE;
var guidance = new ArrayList<String>();
if (readable) guidance.add("No migration is required. Keep readable historical and COMPLETED Works in their existing formats.");
else guidance.add("Unsupported versions require a compatible CLI; invalid files require deliberate repair. No migration route is inferred.");
guidance.add("onboard refreshes entry instructions only, with backups; it does not convert Works or their history.");
guidance.add("Compatibility describes storage readability, not completion readiness or evidence integrity. Run aie project validate separately.");
return new Report(1, ProtocolContract.CLI_VERSION, ProtocolContract.CURRENT, ProtocolContract.READABLE,
FormatVersions.supported(), state, readable, false, findings, guidance);
}
private void inspectRecord(Path root, Path path, RecordType type, List<Finding> findings) {
inspect(root, relative(root, path), type.area(), type.type(), type.bodyField(), true, findings);
}
private static String relative(Path root, Path path) { return root.relativize(path).toString(); }
private void visit(Path root, Path directory, List<Finding> findings, java.util.function.Consumer<Path> operation) {
try {
Path safe = Filespace.resolve(root, relative(root, directory));
for (Path child : Filespace.children(safe)) {
try { operation.accept(Filespace.resolve(root, relative(root, child))); }
catch (RuntimeException e) { invalid(findings, relative(root, child), "directory", e.getMessage()); }
}
} catch (RuntimeException e) { invalid(findings, relative(root, directory), "directory", e.getMessage()); }
}
private static void invalid(List<Finding> findings, String path, String type, String message) {
findings.add(new Finding(path, type, State.INVALID, Map.of(), List.of(), message == null ? "Cannot inspect record" : message));
}
private static final class UnsupportedFormat extends RuntimeException {
UnsupportedFormat(String message) { super(message); }
}
private boolean version(ObjectNode metadata, String field, Integer defaultVersion, FormatVersions.Format format, Map<String, String> versions) {
var value = metadata.get(field);
versions.put(field, value == null ? defaultVersion == null ? "missing" : "implicit " + defaultVersion : value.toString());
int actual;
if (value == null && defaultVersion != null) actual = defaultVersion;
else {
if (value == null || !value.isIntegralNumber() || value.bigIntegerValue().signum() <= 0)
throw ProtocolException.validation(field + " must be a positive integer");
if (!value.canConvertToInt()) throw new UnsupportedFormat("Unsupported " + field + ": " + value);
actual = value.intValue();
}
if (!format.supports(actual)) throw new UnsupportedFormat("Unsupported " + field + ": " + actual);
return actual != format.currentWriteVersion();
}
private void inspect(Path root, String relative, String name, Class<?> type, String bodyField, boolean markdown, List<Finding> findings) {
var versions = new LinkedHashMap<String, String>(); var missing = new ArrayList<String>();
try {
Path path = Filespace.resolve(root, relative);
boolean json = type == ProtocolGuide.Manifest.class || type == PlanCoordinator.Receipt.class || type == EpicCoordinator.Receipt.class;
ObjectNode metadata = markdown ? Documents.metadata(path) : json
? Documents.readJson(path, ObjectNode.class) : Documents.read(path, ObjectNode.class);
if (metadata == null) throw ProtocolException.validation("Expected record object");
var format = type == WorkService.Sequence.class ? FormatVersions.SEQUENCE
: type == ProtocolGuide.Manifest.class ? FormatVersions.MANIFEST : FormatVersions.SCHEMA;
boolean legacy = version(metadata, "schemaVersion", null, format, versions);
if (markdown) legacy |= version(metadata, "documentVersion", 1,
bodyField == null ? FormatVersions.METADATA : FormatVersions.DOCUMENT, versions);
if (type == ProtocolGuide.Manifest.class) {
legacy |= version(metadata, "protocolVersion", 1,
new FormatVersions.Format("protocol-contract", ProtocolContract.CURRENT, ProtocolContract.READABLE), versions);
if (!metadata.has("protocolVersion")) { legacy = true; missing.add("protocolVersion"); }
}
if (type == Work.class) for (String field : WORK_DEFAULTS) if (!metadata.has(field)) { missing.add(field); legacy = true; }
if (markdown) Documents.readMarkdownDocument(path, type, bodyField);
else if (json) Documents.readJson(path, type);
else Documents.read(path, type);
findings.add(new Finding(relative, name, legacy ? State.LEGACY_COMPATIBLE : State.CURRENT, versions, missing,
legacy ? "Readable legacy format; defaults are interpreted in memory. No migration required."
: "Readable current format."));
} catch (UnsupportedFormat e) {
findings.add(new Finding(relative, name, State.UNSUPPORTED, versions, missing, e.getMessage() + "; use a compatible CLI."));
} catch (RuntimeException e) {
findings.add(new Finding(relative, name, State.INVALID, versions, missing, e.getMessage() == null ? "Invalid record" : e.getMessage()));
}
}
}
@@ -261,10 +261,12 @@ public final class VerificationService {
}
public record Action(String code, String workId, String message, String command) {}
public record WorkSummary(String id, String title, Work.Status status, boolean archived, ValidationReport validation, List<Action> nextActions) {}
public record ProjectStatus(int schemaVersion, ProjectConfig.Identity project, boolean onboarded, List<WorkSummary> works) {}
public record ProjectStatus(int schemaVersion, ProjectConfig.Identity project, boolean onboarded, List<WorkSummary> works,
CompatibilityService.Summary compatibility) {}
public ProjectStatus status(Path root, boolean all) {
return new ProjectStatus(1, projects.load(root).project(), ProtocolGuide.installed(root), works.list(root).stream()
.filter(w -> all || !w.archived()).map(w -> new WorkSummary(w.id(), w.title(), w.status(), w.archived(), work(root, w.id()), actions(root, w))).toList());
.filter(w -> all || !w.archived()).map(w -> new WorkSummary(w.id(), w.title(), w.status(), w.archived(), work(root, w.id()), actions(root, w))).toList(),
new CompatibilityService().inspect(root).summary());
}
public List<Action> nextActions(Path root, String id) {
var result = new ArrayList<Action>();
+34
View File
@@ -24,6 +24,40 @@ Use `ai-engineering` (or its installed alias `aie`). No server or model API is n
whole lists. Use DEC drafts for significant commitments; small work need not
invent a decision or plan merely to satisfy a ceremony.
## Compatibility and protocol updates
Run `aie project compatibility --format json` before considering an update. `status`
includes a compatibility summary and the diagnostic command. The diagnostic is
read-only: it inspects actual canonical files and record revisions, without locks,
backups, model calls or migrations. It includes AIE completion receipts, while ignored
runs, local backups and ordinary artifact payloads are excluded. Use `project validate`
for integrity.
`protocol.json` separates `schemaVersion` (the manifest shape) from `protocolVersion`
(the engineering contract revision). A missing `protocolVersion` denotes the legacy
baseline contract 1. The report exposes the installed CLI release, supported contract
versions, format catalog, observed versions and missing defaulted Work fields.
Storage `schemaVersion` and narrative `documentVersion` remain independent.
States are `CURRENT`, `LEGACY_COMPATIBLE`, `UNSUPPORTED` and `INVALID`. The first two
are readable, return exit 0 and do not require migration. Unsupported or invalid
records return exit 4 with file-specific diagnostics. A newer manifest does not prove
that old records were converted. A missing optional field is not by itself a defect.
Compatibility is separate from structural validation and completion readiness.
Keep historical and COMPLETED Works in their original formats. The CLI reads older
supported representations and applies documented defaults in memory, preserving
IDs, approvals, evidence, completion provenance and content hashes. Never reopen or
rewrite a completed Work merely to materialize current fields, topics or surveys.
`aie onboard` refreshes the entry instructions and manifest, with backups, while
leaving Works, evidence and revision history unchanged. A newer unsupported manifest
or contract is refused rather than overwritten; use a compatible CLI. No required
migration is registered in this release. Future conversions must have an explicit
public command, scope, preview, backups and repeatable execution. Do not invent a
migration or inspect AIE source code to discover consumer update procedures; report
public-interface gaps with evidence instead.
## Topics, surveys and refinement
Discussion remains the refinement space: receive ideas, organize topics, investigate,
+2 -1
View File
@@ -1,5 +1,6 @@
{
"schemaVersion": 1,
"protocolVersion": 1,
"protocol": "ai-engineering",
"entrypoint": "README.md",
"instructions": "AGENTS.md",
@@ -8,7 +9,7 @@
"command": "ai-engineering",
"aliases": ["aie"],
"startup": ["status --format json", "next-actions --format json", "work context <WRK> --format markdown"],
"capabilities": ["work", "discussion", "topics", "surveys", "answer-history", "proposal-dispositions", "fixture-adapters", "local-cli-adapters", "guided-agent-setup", "agent-doctor", "agent-routing", "run-provenance", "epic", "epic-policy-authorization", "epic-propagation", "epic-reconciliation", "decision-approval", "decision-history", "planning", "step-dependencies", "evidence", "completion", "plan-consolidation", "cancelled-scope-review", "work-reconciliation", "archive", "reopen"],
"capabilities": ["protocol-compatibility", "work", "discussion", "topics", "surveys", "answer-history", "proposal-dispositions", "fixture-adapters", "local-cli-adapters", "guided-agent-setup", "agent-doctor", "agent-routing", "run-provenance", "epic", "epic-policy-authorization", "epic-propagation", "epic-reconciliation", "decision-approval", "decision-history", "planning", "step-dependencies", "evidence", "completion", "plan-consolidation", "cancelled-scope-review", "work-reconciliation", "archive", "reopen"],
"humanApproval": "explicit-attestation",
"execution": "external-human-or-agent",
"legacyImport": false
@@ -0,0 +1,173 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.cli.EngineeringCli;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.verification.*;
import net.intrepid.aiengineering.work.*;
import tools.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import static org.assertj.core.api.Assertions.*;
import static net.intrepid.aiengineering.verification.CompatibilityService.State.*;
class CompatibilityTest {
@TempDir Path root;
private record Result(int code, String out, String err) {}
private Result run(String... args) {
var out = new StringWriter(); var err = new StringWriter();
int code = new EngineeringCli(root).execute(new PrintWriter(out), new PrintWriter(err), args);
return new Result(code, out.toString(), err.toString());
}
private String ok(String... args) {
var result = run(args); assertThat(result.code()).as(result.err() + result.out()).isZero(); return result.out();
}
private void init() { ok("init", "--name", "Test"); }
private Path work() { return root.resolve(".ai-engineering/works/WRK-0001-delivered-baseline"); }
private CompatibilityService.Report inspect() { return new CompatibilityService().inspect(root); }
private Map<String, String> snapshot(Path directory) throws Exception {
var result = new TreeMap<String, String>();
try (var paths = Files.walk(directory)) {
for (Path path : paths.filter(Files::isRegularFile).toList())
result.put(directory.relativize(path).toString(), Base64.getEncoder().encodeToString(Files.readAllBytes(path)));
}
return result;
}
private void baseline() throws Exception {
init(); ok("work", "create", "Delivered baseline");
Path fixtures = Path.of(getClass().getResource("/compatibility/baseline-v1/.ai-engineering").toURI());
try (var files = Files.walk(fixtures)) {
for (Path path : files.filter(Files::isRegularFile).toList()) {
Path target = root.resolve(".ai-engineering").resolve(fixtures.relativize(path));
Files.createDirectories(target.getParent()); Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
}
}
}
@Test void currentProjectExposesSupportedFormatsAndDoesNotWriteDuringInspection() throws Exception {
init(); var before = snapshot(root);
var report = inspect();
assertThat(report.state()).isEqualTo(CURRENT); assertThat(report.readable()).isTrue();
assertThat(report.migrationRequired()).isFalse();
assertThat(report.currentProtocolVersion()).isEqualTo(1);
assertThat(report.formats()).contains(FormatVersions.SEQUENCE, FormatVersions.DOCUMENT);
assertThat(ok("project", "compatibility", "--format", "json")).contains("\"cliVersion\"", "\"readableVersions\"", "\"migrationRequired\" : false");
assertThat(ok("status", "--format", "json")).contains("\"compatibility\"", "\"state\" : \"CURRENT\"");
assertThat(snapshot(root)).isEqualTo(before);
}
@Test void frozenDeliveredWorkRetainsMeaningApprovalsEvidenceAndBytesAcrossReadsAndOnboarding() throws Exception {
baseline(); var before = snapshot(root); var historical = snapshot(root.resolve(".ai-engineering/works"));
var service = new VerificationService();
var context = service.context(root, "WRK-0001");
assertThat(context.work().status()).isEqualTo(Work.Status.COMPLETED);
assertThat(context.work().topics()).isEmpty(); assertThat(context.work().epic()).isFalse();
assertThat(context.decisions().getFirst().approvalStatus().name()).isEqualTo("ACCEPTED");
assertThat(context.work().completions().getFirst().origin()).isEqualTo(Work.CompletionOrigin.HUMAN);
assertThat(context.work().completions().getFirst().humanApproved()).isTrue();
String digest = context.work().completions().getFirst().scopeHash();
assertThat(service.scopeHash(root, context.work())).isEqualTo(digest);
var report = inspect(); assertThat(report.state()).isEqualTo(LEGACY_COMPATIBLE);
assertThat(report.readable()).isTrue(); assertThat(report.migrationRequired()).isFalse();
assertThat(report.findings()).anySatisfy(finding -> {
assertThat(finding.recordType()).isEqualTo("work");
assertThat(finding.missingFields()).contains("topics", "agentRuns", "epic");
});
for (String[] args : List.of(new String[]{"project", "compatibility", "--format", "json"},
new String[]{"project", "validate"}, new String[]{"status"}, new String[]{"next-actions"},
new String[]{"work", "context", "WRK-0001"}, new String[]{"decision", "history", "WRK-0001", "DEC-0001"})) ok(args);
assertThat(snapshot(root)).isEqualTo(before);
ok("onboard");
assertThat(snapshot(root.resolve(".ai-engineering/works"))).isEqualTo(historical);
var after = service.context(root, "WRK-0001");
assertThat(after.work()).isEqualTo(context.work()); assertThat(after.decisions()).isEqualTo(context.decisions());
assertThat(after.discussionHistory()).isEqualTo(context.discussionHistory()); assertThat(after.artifacts()).isEqualTo(context.artifacts());
assertThat(service.scopeHash(root, after.work())).isEqualTo(digest);
assertThat(inspect().state()).isEqualTo(LEGACY_COMPATIBLE); // refreshing the manifest did not migrate the Work.
ok("project", "validate");
assertThat(snapshot(root.resolve(".ai-engineering/works"))).isEqualTo(historical);
}
@Test void newerContractsAreDiagnosableAndCannotBeSilentlyDowngraded() throws Exception {
init(); Path manifest = root.resolve(".ai-engineering/protocol.json"); String original = Files.readString(manifest);
for (String field : List.of("protocolVersion", "schemaVersion")) {
var metadata = Documents.parseJson(original, ObjectNode.class); metadata.put(field, 99);
Files.writeString(manifest, Documents.json(metadata)); var before = snapshot(root);
assertThat(inspect().state()).isEqualTo(UNSUPPORTED); assertThat(inspect().migrationRequired()).isFalse();
var result = run("project", "compatibility", "--format", "json");
assertThat(result.code()).isEqualTo(4); assertThat(result.out()).contains("UNSUPPORTED", field, "99");
assertThat(run("onboard").code()).isEqualTo(4);
assertThat(run("work", "create", "Do not write").code()).isEqualTo(4);
assertThat(snapshot(root)).isEqualTo(before);
}
}
@Test void manifestCannotHideAnUnsupportedWorkOrHistoricalRevision() throws Exception {
baseline(); ok("onboard"); // current manifest, with genuine old formats beneath it.
Path prior = work().resolve("decisions/.history/DEC-0001/r0001.md"); String original = Files.readString(prior);
Files.writeString(prior, original.replace("\"schemaVersion\": 1", "\"schemaVersion\": 77"));
var before = snapshot(root); var report = inspect();
assertThat(report.readable()).isFalse(); assertThat(report.state()).isEqualTo(UNSUPPORTED);
assertThat(report.findings()).anySatisfy(finding -> {
assertThat(finding.path()).endsWith("decisions/.history/DEC-0001/r0001.md");
assertThat(finding.state()).isEqualTo(UNSUPPORTED);
});
assertThat(snapshot(root)).isEqualTo(before);
Files.writeString(prior, original);
Path path = work().resolve("work.md"); String work = Files.readString(path);
Files.writeString(path, work.replace("\"schemaVersion\": 1", "\"schemaVersion\": 88"));
assertThat(inspect().state()).isEqualTo(UNSUPPORTED);
assertThat(run("project", "compatibility").code()).isEqualTo(4);
}
@Test void incompatibleDocumentsAndMalformedVersionsAreReportedWithoutMutation() throws Exception {
baseline(); Path entry = work().resolve("discussions/DSC-0001.md"); String original = Files.readString(entry);
for (String version : List.of("99", "99999999999999999999999", "\"2\"", "null", "0", "-1", "2.5")) {
// Use a valid YAML envelope so that the version itself, rather than YAML syntax, is diagnosed.
var metadata = Documents.parse(original.substring(4, original.lastIndexOf("---")), ObjectNode.class);
String yaml = Documents.yaml(metadata).replaceFirst("^---\\n", "");
Files.writeString(entry, "---\n" + yaml + "documentVersion: " + version + "\n---\n");
var before = snapshot(root); var finding = inspect().findings().stream().filter(f -> f.path().endsWith("discussions/DSC-0001.md")).findFirst().orElseThrow();
assertThat(finding.state()).isEqualTo(version.startsWith("99") ? UNSUPPORTED : INVALID);
assertThat(snapshot(root)).isEqualTo(before);
}
}
@Test void missingReferencesAndUnknownFieldsAreNotLabelledLegacyCompatible() throws Exception {
baseline(); Path path = work().resolve("discussions/DSC-0001.md"); String original = Files.readString(path);
Files.delete(path); assertThat(inspect().state()).isEqualTo(INVALID);
Files.writeString(path, original.replace("\"schemaVersion\": 1", "\"unknownField\": true,\n\"schemaVersion\": 1"));
assertThat(inspect().state()).isEqualTo(INVALID);
}
@Test void completionReceiptFormatsAreInspectedButOrdinaryEvidenceIsNotParsedAsProtocol() throws Exception {
init(); ok("work", "create", "Plan delivery");
Files.writeString(root.resolve("evidence.txt"), "This is evidence, not YAML or JSON.\n");
ok("artifact", "add", "WRK-0001", "--file", "evidence.txt", "--purpose", "Observed test result");
ok("plan", "create", "WRK-0001", "--title", "Delivery");
ok("plan", "step", "add", "WRK-0001", "PLN-0001", "--title", "Verify");
ok("plan", "step", "status", "WRK-0001", "PLN-0001", "TSK-0001", "COMPLETED", "--by", "agent", "--reason", "Verified", "--evidence", "ART-0001");
assertThat(inspect().state()).isEqualTo(CURRENT);
var receipt = inspect().findings().stream().filter(f -> f.recordType().equals("completion-receipt")).findFirst().orElseThrow();
Path path = root.resolve(receipt.path()); var metadata = Documents.readJson(path, ObjectNode.class);
metadata.put("schemaVersion", 99); Files.writeString(path, Documents.json(metadata));
var before = snapshot(root);
assertThat(inspect().findings()).anySatisfy(finding -> {
assertThat(finding.recordType()).isEqualTo("completion-receipt");
assertThat(finding.state()).isEqualTo(UNSUPPORTED);
});
assertThat(snapshot(root)).isEqualTo(before);
}
@Test void projectWithoutDiscoveryFilesRemainsReadableAndInspectionIsIdempotent() throws Exception {
init();
for (String file : List.of("README.md", "AGENTS.md", "protocol.json")) Files.delete(root.resolve(".ai-engineering/" + file));
var before = snapshot(root); String first = ok("project", "compatibility", "--format", "json");
assertThat(first).contains("LEGACY_COMPATIBLE", "No discovery manifest");
assertThat(ok("project", "compatibility", "--format", "json")).isEqualTo(first);
assertThat(snapshot(root)).isEqualTo(before); ok("project", "validate");
}
@Test void diagnosticRejectsSymlinksWithoutReadingTheTarget() throws Exception {
init(); Path outside = Files.createTempFile("aie-compatibility-outside-", ".txt");
Files.writeString(outside, "PRIVATE TARGET CONTENT");
Path manifest = root.resolve(".ai-engineering/protocol.json"); Files.delete(manifest); Files.createSymbolicLink(manifest, outside);
var result = run("project", "compatibility", "--format", "json");
assertThat(result.code()).isEqualTo(2); assertThat(result.err()).contains("Symlink rejected").doesNotContain("PRIVATE TARGET CONTENT");
}
}
@@ -105,7 +105,7 @@ class ProtocolIntegrationTest {
}
@Test void cliSmokeAndHelpForEveryCommand() {
assertThat(ok("--version").out()).isEqualTo("ai-engineering 0.1.0\n");
for (String command : new String[]{"", "init", "project", "project show", "project validate", "repo", "repo add", "repo list",
for (String command : new String[]{"", "init", "project", "project show", "project validate", "project compatibility", "repo", "repo add", "repo list",
"work", "work create", "work update", "work list", "work show", "work validate", "work context", "discussion", "discussion add",
"discussion list", "discussion migrate", "decision", "decision draft", "decision list", "decision show", "decision update",
"decision accept", "decision reject", "decision revise", "decision history", "artifact", "artifact add",
@@ -0,0 +1,20 @@
# Frozen compatibility baseline
`baseline-v1/.ai-engineering` was created and validated on 2026-11-16 using the
previous installed 0.1.0 native executable, before adding `protocolVersion` and
`project compatibility`. Retain these bytes when changing writers or readers.
The fixture contains a pre-versioned manifest, schema 1 Work counter, completed
Work, accepted decision and its draft revision, a discussion and owned evidence.
The discussion and draft were stored in the supported YAML-only representation;
empty optional Work fields and default human completion provenance were omitted.
The previous executable successfully ran `project validate` after those omissions.
The original completion scope hash, approval history and evidence digests are retained.
This is synthetic test data. Its human approval attestations belong to the fixture,
not to a real user's project delivery. The files use JSON as YAML front matter where
convenient; JSON mappings are valid YAML, independent of current writer formatting.
Tests install this frozen state in temporary projects, create required empty
directories, and check interpretation and byte preservation. Do not regenerate the
baseline using a new writer just to make a compatibility regression pass.
@@ -0,0 +1,7 @@
---
schemaVersion: 1
project:
id: "historical-project"
name: "Historical Project"
repositories: []
agents: null
@@ -0,0 +1,15 @@
{
"schemaVersion": 1,
"protocol": "ai-engineering",
"entrypoint": "README.md",
"instructions": "AGENTS.md",
"configuration": "ai-engineering.yaml",
"works": "works",
"command": "ai-engineering",
"aliases": ["aie"],
"startup": ["status --format json", "next-actions --format json", "work context <WRK> --format markdown"],
"capabilities": ["work", "discussion", "topics", "surveys", "answer-history", "proposal-dispositions", "fixture-adapters", "local-cli-adapters", "guided-agent-setup", "agent-doctor", "agent-routing", "run-provenance", "epic", "epic-policy-authorization", "epic-propagation", "epic-reconciliation", "decision-approval", "decision-history", "planning", "step-dependencies", "evidence", "completion", "plan-consolidation", "cancelled-scope-review", "work-reconciliation", "archive", "reopen"],
"humanApproval": "explicit-attestation",
"execution": "external-human-or-agent",
"legacyImport": false
}
@@ -0,0 +1,2 @@
schemaVersion: 1
lastWork: 1
@@ -0,0 +1,11 @@
---
schemaVersion: 1
id: "ART-0001"
workId: "WRK-0001"
origin: "evidence.txt"
purpose: "Verified historical fixture evidence"
path: "artifacts/evidence/ART-0001/payload"
sha256: "98545564d0747210b91b933bf8554c4b7e36ba878e6662cb48156b08ff74e1ee"
size: 59
author: "owner"
createdAt: "2026-11-16T09:55:00.851736Z"
@@ -0,0 +1 @@
Historical fixture: observed result and successful checks.
@@ -0,0 +1,18 @@
---
{
"schemaVersion": 1,
"id": "DEC-0001",
"workId": "WRK-0001",
"title": "Retain delivered evidence",
"context": "Historical baseline",
"approach": "Retain the evidence",
"alternatives": [],
"rationale": "Preserve the reviewed result",
"risks": [],
"acceptanceCriteria": [],
"approvalStatus": "DRAFT",
"author": "owner",
"createdAt": "2026-11-16T09:54:59.755370Z",
"evidence": []
}
---
@@ -0,0 +1,31 @@
---
schemaVersion: 1
id: "DEC-0001"
workId: "WRK-0001"
title: "Retain delivered evidence"
context: "Historical baseline"
approach: "Retain the evidence"
alternatives: []
rationale: "Preserve the reviewed result"
risks: []
acceptanceCriteria: []
approvalStatus: "ACCEPTED"
author: "owner"
createdAt: "2026-11-16T09:54:59.755370Z"
evidence: []
revision: 2
previousHash: "545dc8e36da222fdeaf9458f77880bf2d1842738b82bac5296cddf62452a7e01"
updatedAt: "2026-11-16T09:55:00.238007Z"
updatedBy: "owner"
changeReason: "Fixture: explicit historical approval"
approvals:
- status: "ACCEPTED"
by: "owner"
reason: "Fixture: explicit historical approval"
at: "2026-11-16T09:55:00.237982Z"
humanApproved: true
revises: null
supersededBy: null
documentVersion: 2
---
@@ -0,0 +1,13 @@
---
{
"schemaVersion": 1,
"id": "DSC-0001",
"workId": "WRK-0001",
"discussionId": "main",
"kind": "NOTE",
"author": "owner",
"createdAt": "2026-11-16T09:54:59.319973Z",
"respondsTo": null,
"text": "Historical observation: baseline verified in a prior release."
}
---
@@ -0,0 +1,57 @@
---
{
"schemaVersion": 1,
"id": "WRK-0001",
"title": "Delivered baseline",
"description": "",
"goal": "Preserve the verified historical result",
"motivation": "",
"constraints": [],
"acceptanceCriteria": [
"Historical evidence remains interpretable"
],
"status": "COMPLETED",
"createdAt": "2026-11-16T09:54:59.082762Z",
"updatedAt": "2026-11-16T09:55:01.355514Z",
"author": "owner",
"repositories": [],
"discussions": [
"DSC-0001"
],
"decisions": [
"DEC-0001"
],
"artifacts": [
"ART-0001"
],
"completions": [
{
"at": "2026-11-16T09:55:01.355514Z",
"by": "owner",
"summary": "Fixture delivery verified in a prior executable",
"humanApproved": true,
"scopeHash": "72d5803add0b8714d7dc4bf7e63ad55cc3259df910aa8b03790657eac4c2bd02",
"criteria": [
{
"criterion": 1,
"text": "Historical evidence remains interpretable",
"evidence": [
"ART-0001"
]
}
],
"integrations": [],
"noIntegrationReason": "Historical inspection fixture"
}
],
"events": [
{
"action": "COMPLETE",
"by": "owner",
"reason": "Fixture delivery verified in a prior executable",
"at": "2026-11-16T09:55:01.355514Z"
}
],
"archived": false
}
---