feat: add tabular Work summaries and CSV exports
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/AI Engineering/pipeline/head There was a failure building this commit
build / jvm (push) Canceled after 0s
build / native (macos-15, macos-arm64) (push) Canceled after 0s
build / native (ubuntu-24.04, linux-x86_64) (push) Canceled after 0s
build / native (windows-2025, windows-x86_64) (push) Canceled after 0s

This commit is contained in:
Nilton Constantino
2026-11-16 15:59:26 +00:00
parent f296d252c6
commit a7e3a2fdfc
21 changed files with 642 additions and 5 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
---
schemaVersion: 2
lastWork: "0009"
lastWork: "000A"
@@ -0,0 +1,12 @@
---
schemaVersion: 1
id: "ART-0001"
workId: "WRK-000A"
origin: "aie-wrk000a-validation.txt"
purpose: "Resultados observados dos 155 testes, pipeline, formatos e smoke nativo,\
\ validação e instalação; hashes das fontes e binário"
path: "artifacts/evidence/ART-0001/payload"
sha256: "3d47754ce8c7749af704bf4aa8b15275b82b28f5c88d09ac865b7e715be5aa13"
size: 2826
author: "codex"
createdAt: "2026-11-16T15:53:55.415467Z"
@@ -0,0 +1,31 @@
WRK-000A validation observed 2026-11-16T15:53:49.030062+00:00
Authorized scope: DSC-0001 records the explicit user instruction to proceed.
Implementation: table/CSV/Markdown listings for work list, status and next-actions; work list --open; unchanged complete JSON contracts.
Commands executed successfully in this session:
./gradlew compileJava --console=plain
./gradlew test check --console=plain (BUILD SUCCESSFUL in 6m 56s)
JUnit results: {'tests': 155, 'failures': 0, 'errors': 0, 'skipped': 0}
ListingTest: 4 integration tests passed. Coverage includes all formats, open/active/blocked/terminal/archived Works, progress across multiple Plans including cancelled steps, escaping multiline fields, empty lists, invalid plans, original JSON payloads and byte-for-byte unchanged project files during reads.
Jenkins pipeline fixture: 11 success/failure scenarios passed.
GRAALVM_HOME/JAVA_HOME=installed GraalVM JDK25 ./gradlew nativeCompile --console=plain (BUILD SUCCESSFUL)
bash scripts/native-smoke.sh /Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/nativeCompile/ai-engineering (exit 0; all native scenarios passed, including new table/CSV/Markdown checks without JVM/Git/providers)
Python stdlib csv.DictReader parsed actual native work list CSV: 10 rows; IDs/titles/status match full JSON; 8 columns per row and CRLF endings; --open selected only WRK-000A before completion.
Native project validate --format json: valid=true, issues=[].
./scripts/install-native.sh (exit 0; updated ~/.local/bin/ai-engineering and aie shortcut)
Installed aie work list --open --format table: displayed WRK-000A with 0/1 steps and valid validation before completion.
Installed aie next-actions WRK-000A --format csv: valid four-column header and EXECUTE_STEP row.
git diff --check (exit 0)
Installed binary SHA-256: d39b42175f1b0594660b076b4fb6659865bfc283106442920f1f43b0484c4809
Verified installed binary is byte-for-byte identical to the native build tested above.
Source SHA-256 (uncommitted workspace contents):
7c96e797da9e7088d673f2ae951d56f97c2b9b3ab7269369e4400cd1aa030a50 src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java
3c0c09194d91aed4a358a29b1f77c809d2db340bac13f8f22b9db6eb29717ecc src/main/java/net/intrepid/aiengineering/cli/Listing.java
b8551ac790af95f82489fce6ef318e12fe906f5a3e57855bb39b509028a5bfa2 src/main/java/net/intrepid/aiengineering/verification/VerificationService.java
5c86613907627912a479b46042bb3ec1773ad320fb1df4b0a1f140cfff813d37 src/test/java/net/intrepid/aiengineering/ListingTest.java
a749f98d13c0cc5e558ef9691cc6d5420932986f1ef447634968148b22f553b3 scripts/native-smoke.sh
af6bbbae96505f20634d9ba41d66bd46dab94d4e62105a2c9a3f762cf01e9d9e README.md
5905f6795792a2e8f122c26f95bbe0fe25a3a68fbe09ff7c400a8cda9ce6e0d6 docs/protocol.md
@@ -0,0 +1,12 @@
---
schemaVersion: 1
id: "ART-0002"
workId: "WRK-000A"
origin: "ai-engineering:plans:c1d5c0b6454c4a31f6755aa44432cb2d06ffe3fedcc9987969b4fac0635c05b5"
purpose: "Deterministic aggregation of completed Plans and reviewed cancellations;\
\ not semantic verification of prose criteria"
path: "artifacts/evidence/ART-0002/payload"
sha256: "c1d5c0b6454c4a31f6755aa44432cb2d06ffe3fedcc9987969b4fac0635c05b5"
size: 283
author: "system:plans"
createdAt: "2026-11-16T15:54:04.222353Z"
@@ -0,0 +1,10 @@
{
"schemaVersion" : 1,
"workId" : "WRK-000A",
"inputHash" : "2740eee2847b43de325e3f02431980c21b3ca8530935b793921312e4271fd299",
"plans" : [ {
"id" : "PLN-0001",
"revision" : 5,
"sha256" : "99f2252e73cd0cf59eafaa76e889070875d25d5e78f27759e0935e06e0c1d573"
} ]
}
@@ -0,0 +1,13 @@
---
schemaVersion: 1
id: "DSC-0001"
workId: "WRK-000A"
discussionId: "main"
kind: "CONCLUSION"
author: "user"
createdAt: "2026-11-16T15:41:40.372772Z"
respondsTo: null
documentVersion: 2
---
Aprovação explícita do recorte proposto: após a proposta de table e csv para work list/status/next-actions, tabela Markdown e filtro --open, o usuário respondeu: perfeito, sigamos com isso. Implementação autorizada nesse escopo.
@@ -0,0 +1,13 @@
---
schemaVersion: 1
id: "DSC-0002"
workId: "WRK-000A"
discussionId: "main"
kind: "NOTE"
author: "codex"
createdAt: "2026-11-16T15:49:38.440882Z"
respondsTo: null
documentVersion: 2
---
Implementação em andamento: formatos tabulares restritos a work list/status/next-actions, com enum próprio para não aceitar silenciosamente formatos novos nos demais comandos. JSON mantém os payloads completos existentes. Steps representa COMPLETED/total de passos registrados em todos os Plans, incluindo cancelados no total; 0/0 sem passos e unavailable se dados do Plan forem ilegíveis. Pending actions conta as sugestões determinísticas existentes, inclusive manutenção; próximo comando é a primeira sugestão, sem priorização nova. Work list --open inclui OPEN/ACTIVE/BLOCKED não arquivados. CSV usa cabeçalho estável, CRLF e quoting para vírgula, aspas e quebras; Markdown escapa texto e table mantém os valores completos em linhas únicas.
@@ -0,0 +1,13 @@
---
schemaVersion: 1
id: "DSC-0003"
workId: "WRK-000A"
discussionId: "main"
kind: "CONCLUSION"
author: "codex"
createdAt: "2026-11-16T15:53:49.387525Z"
respondsTo: null
documentVersion: 2
---
Entregue o recorte aprovado: table/csv/Markdown em work list/status/next-actions e filtro --open em todos os formatos de work list; JSON completo preservado. 155 testes JVM passaram sem falhas/skip, incluindo os 4 testes novos; fixture Jenkins com 11 cenários e todos os smokes nativos passaram. CSV nativo conferido por csv.DictReader contra JSON. Validação do projeto passou. O instalador atualizou ~/.local/bin e os comandos foram conferidos com o aie instalado. Evidências e hashes serão vinculados ao passo do Plan; a conclusão segue a consolidação automática existente.
@@ -0,0 +1,19 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-000A"
title: "Implementar e validar listagens resumidas"
decisions: []
steps: []
status: "OPEN"
author: "codex"
createdAt: "2026-11-16T15:41:41.037540Z"
revision: 1
previousHash: null
updatedAt: "2026-11-16T15:41:41.037540Z"
updatedBy: "codex"
changeReason: "Plan created"
documentVersion: 2
---
Adicionar projeção de progresso e ações existentes, renderizadores table/CSV/Markdown restritos às listagens, filtro --open, documentação e testes de integração. Preservar JSON completo.
@@ -0,0 +1,30 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-000A"
title: "Implementar e validar listagens resumidas"
decisions: []
steps:
- id: "TSK-0001"
title: "Entregar formatos de listagem e filtro --open"
description: ""
acceptanceCriteria:
- "CLI, testes e documentação cobrem os formatos, progresso real, filtro e compatibilidade\
\ JSON."
dependsOn: []
status: "OPEN"
result: ""
evidence: []
updatedAt: "2026-11-16T15:41:43.012693Z"
status: "OPEN"
author: "codex"
createdAt: "2026-11-16T15:41:41.037540Z"
revision: 2
previousHash: "77565eeb2deeb2d07069080fcf255c84d50ffade20e495f64a4cdcf11d1599bd"
updatedAt: "2026-11-16T15:41:43.012787Z"
updatedBy: "codex"
changeReason: "Escopo aprovado explicitamente pelo usuário"
documentVersion: 2
---
Adicionar projeção de progresso e ações existentes, renderizadores table/CSV/Markdown restritos às listagens, filtro --open, documentação e testes de integração. Preservar JSON completo.
@@ -0,0 +1,30 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-000A"
title: "Implementar e validar listagens resumidas"
decisions: []
steps:
- id: "TSK-0001"
title: "Entregar formatos de listagem e filtro --open"
description: ""
acceptanceCriteria:
- "CLI, testes e documentação cobrem os formatos, progresso real, filtro e compatibilidade\
\ JSON."
dependsOn: []
status: "ACTIVE"
result: "Início da implementação autorizada"
evidence: []
updatedAt: "2026-11-16T15:41:45.279481Z"
status: "ACTIVE"
author: "codex"
createdAt: "2026-11-16T15:41:41.037540Z"
revision: 3
previousHash: "e75afb8938189ab5064353d7d60defeead71b807acf32b525a25a781531b539f"
updatedAt: "2026-11-16T15:41:45.279519Z"
updatedBy: "codex"
changeReason: "Início da implementação autorizada"
documentVersion: 2
---
Adicionar projeção de progresso e ações existentes, renderizadores table/CSV/Markdown restritos às listagens, filtro --open, documentação e testes de integração. Preservar JSON completo.
@@ -0,0 +1,35 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-000A"
title: "Implementar e validar listagens resumidas"
decisions: []
steps:
- id: "TSK-0001"
title: "Entregar formatos de listagem e filtro --open"
description: ""
acceptanceCriteria:
- "CLI, testes e documentação cobrem os formatos, progresso real, filtro e compatibilidade\
\ JSON."
dependsOn: []
status: "COMPLETED"
result: "Formatos table/CSV/Markdown e --open entregues; 155 testes e 11 cenários\
\ de pipeline passando, todos os smokes nativos e validação aprovados; CLI local\
\ atualizado e conferido."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T15:54:02.952973Z"
status: "ACTIVE"
author: "codex"
createdAt: "2026-11-16T15:41:41.037540Z"
revision: 4
previousHash: "d9dc3ded5c8f16646c2d755659c47e3afb9b483696367ebe296a9c2305a9dc82"
updatedAt: "2026-11-16T15:54:02.953003Z"
updatedBy: "codex"
changeReason: "Formatos table/CSV/Markdown e --open entregues; 155 testes e 11 cená\
rios de pipeline passando, todos os smokes nativos e validação aprovados; CLI local\
\ atualizado e conferido."
documentVersion: 2
---
Adicionar projeção de progresso e ações existentes, renderizadores table/CSV/Markdown restritos às listagens, filtro --open, documentação e testes de integração. Preservar JSON completo.
@@ -0,0 +1,33 @@
---
schemaVersion: 1
id: "PLN-0001"
workId: "WRK-000A"
title: "Implementar e validar listagens resumidas"
decisions: []
steps:
- id: "TSK-0001"
title: "Entregar formatos de listagem e filtro --open"
description: ""
acceptanceCriteria:
- "CLI, testes e documentação cobrem os formatos, progresso real, filtro e compatibilidade\
\ JSON."
dependsOn: []
status: "COMPLETED"
result: "Formatos table/CSV/Markdown e --open entregues; 155 testes e 11 cenários\
\ de pipeline passando, todos os smokes nativos e validação aprovados; CLI local\
\ atualizado e conferido."
evidence:
- "ART-0001"
updatedAt: "2026-11-16T15:54:02.952973Z"
status: "COMPLETED"
author: "codex"
createdAt: "2026-11-16T15:41:41.037540Z"
revision: 5
previousHash: "f301026cf2bdd4bf17f94ab0351c7be809e2885e2efc4c6fcf5fbc2ad6fb6290"
updatedAt: "2026-11-16T15:54:03.508289Z"
updatedBy: "system:plans"
changeReason: "All required steps completed; reviewed cancellations retained"
documentVersion: 2
---
Adicionar projeção de progresso e ações existentes, renderizadores table/CSV/Markdown restritos às listagens, filtro --open, documentação e testes de integração. Preservar JSON completo.
@@ -0,0 +1,77 @@
---
schemaVersion: 1
id: "WRK-000A"
title: "Listar Works em table, CSV e Markdown com filtro de abertos"
description: "Escopo aprovado na conversa: table e csv em work list, status e next-actions;\
\ tabelas Markdown; filtro --open em work list; preservar JSON completo e derivar\
\ progresso dos passos registrados."
goal: "Facilitar a escolha do próximo Work por listagens resumidas e exportáveis."
motivation: ""
constraints: []
acceptanceCriteria:
- "work list, status e next-actions oferecem table, csv, markdown e json; JSON manté\
m os contratos existentes."
- "work list --open seleciona Works não terminais e não arquivados em qualquer formato;\
\ resumos mostram estado, passos concluídos/total, pendências e próxima ação."
- "Escaping, listas vazias, dados inválidos, leitura sem mutação e regressão dos comandos\
\ são verificados; documentação e CLI executável refletem o comportamento."
status: "COMPLETED"
createdAt: "2026-11-16T15:41:38.883616Z"
updatedAt: "2026-11-16T15:54:04.271359Z"
author: "user"
repositories: []
discussions:
- "DSC-0001"
- "DSC-0002"
- "DSC-0003"
decisions: []
artifacts:
- "ART-0001"
- "ART-0002"
plans:
- "PLN-0001"
completions:
- at: "2026-11-16T15:54:04.271359Z"
by: "system:plans"
summary: "All required Plans completed; requester=codex"
humanApproved: false
scopeHash: "cc0ebda83e732214800eb45c1c1dde0ddb6f534826fac7546776417fa50ff4f5"
criteria:
- criterion: 1
text: "work list, status e next-actions oferecem table, csv, markdown e json;\
\ JSON mantém os contratos existentes."
evidence:
- "ART-0002"
- criterion: 2
text: "work list --open seleciona Works não terminais e não arquivados em qualquer\
\ formato; resumos mostram estado, passos concluídos/total, pendências e pró\
xima ação."
evidence:
- "ART-0002"
- criterion: 3
text: "Escaping, listas vazias, dados inválidos, leitura sem mutação e regressã\
o dos comandos são verificados; documentação e CLI executável refletem o comportamento."
evidence:
- "ART-0002"
integrations: []
noIntegrationReason: "Canonical changes and execution results are recorded in the\
\ Plan step evidence"
origin: "SYSTEM_PLANS"
delegation: null
aggregation:
receipt: "ART-0002"
inputHash: "2740eee2847b43de325e3f02431980c21b3ca8530935b793921312e4271fd299"
requester: "codex"
requestId: "84563805-65a6-48b0-a98f-8123de69f437"
events:
- action: "COMPLETE"
by: "system:plans"
reason: "All required Plans completed; requester=codex"
at: "2026-11-16T15:54:04.271359Z"
archived: false
topics: []
surveys: []
dispositions: []
agentRuns: []
epic: false
---
+33
View File
@@ -149,6 +149,39 @@ The exported context brings together the Work's scope, discussion, decisions,
plans, evidence references, and pending questions. `next-actions` suggests what to
address next. Every command provides `--help`; inspection commands support JSON.
### Choose the next Work
`work list`, `status`, and `next-actions` accept `--format table|csv|markdown|json`.
Markdown is the default and renders actual tables. Use aligned tables in the
terminal, CSV for spreadsheets, and JSON for the existing full structured records:
```sh
aie work list --open --format table
aie status --format table
aie next-actions --format table
aie work list --open --format csv > open-works.csv
aie next-actions WRK-0001 --format csv > next-actions.csv
```
Work summaries show ID, title, status, archive flag, completed/total steps,
pending action count, validation, and the next suggested command. Steps count
all registered Plans, including cancelled steps in the total; `0/0` means no
steps are registered, and `unavailable` means Plan data could not be read.
Pending actions are the deterministic suggestions from `next-actions`, including
execution, questions, decision review, dependencies, repairs, and archival.
They are not a count of blockers or a priority ranking. Use `next-actions WRK`
to inspect every suggestion and its explanation.
`--open` includes OPEN, ACTIVE, and BLOCKED Works and excludes completed,
cancelled, and archived Works, in every format. Without this filter, `work list`
continues to include all Works. `status` hides archived Works unless `--all` is
given. JSON schemas and default formats elsewhere are unchanged. CSV uses UTF-8,
comma separators, a fixed header, CRLF record endings, and quoted fields when
needed; original multiline text is preserved. CSV contains just the table,
including a header for empty results. Markdown escapes cell content and table
output flattens line breaks and control characters. These commands only read
project records and never invoke a model.
### Use existing Git repositories
Git is required when registering or inspecting source repositories. In a project
+24
View File
@@ -180,6 +180,30 @@ Legacy projects with none of the three entry files remain valid. Partial install
malformed/duplicate JSON fields, unknown manifest versions and unsupported paths are
validation failures. `onboard` refreshes the contract while backing up changed files.
`work list`, `status`, and `next-actions` support `--format table|csv|markdown|json`.
Their default Markdown output is a table; `table` aligns columns for terminals,
and CSV provides UTF-8 comma-separated records with stable headers and RFC 4180
quoting/CRLF record endings. CSV emits no project preamble and keeps original
multiline field values. Empty results still have headers. JSON retains its full
existing records (`Work[]`, `ProjectStatus`, and `Action[]`, respectively).
Work table/CSV/Markdown columns are `id`, `title`, `status`, `archived`, `steps`,
`pending_actions`, `validation`, and `next_action` (human formats use display
labels). Progress counts COMPLETED steps over all registered steps across Plans,
including cancelled steps in the denominator. No steps means `0/0`; unreadable
Plan data means `unavailable`, with invalid validation and a repair suggestion.
Pending actions count deterministic suggestions, including execution and
maintenance; they are not solely blockers or semantic progress. The next command
is the first existing suggestion, without a new prioritization algorithm.
Action columns are `work_id`, `code`, `message`, and `command`. A project-level
action has an empty `work_id`. Markdown escapes cell text; terminal tables flatten
line breaks/control characters without truncating field values.
`work list --open` filters every format to nonterminal, unarchived Works: OPEN,
ACTIVE, and BLOCKED. Unfiltered Work lists continue to include archived Works.
Tabular formats apply to these three read commands only; other commands retain
their existing format choices. No storage or protocol revision is required.
An agent begins with the guide, status, next-actions and selected Work context. These
are portable instructions, not an LLM plugin or enforcement mechanism. Without the
CLI, an agent can inspect the files directly. Agents must still inspect the entry
+17
View File
@@ -28,6 +28,23 @@ 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 work list --open --format table > works-table.txt
grep -q 'WRK-0001' works-table.txt
grep -q '0/0' works-table.txt
aie_without_git work list --open --format csv > works.csv
grep -q '^id,title,status,archived,steps,pending_actions,validation,next_action' works.csv
grep -q '^WRK-0001,Continue application,OPEN,false,0/0,' works.csv
aie_without_git work list --format markdown > works.md
grep -Fq '| ID | Title | Status |' works.md
aie_without_git status --format table > status-table.txt
grep -q 'Compatibility: CURRENT' status-table.txt
aie_without_git status --format csv > status.csv
cmp works.csv status.csv
aie_without_git next-actions --format table > actions-table.txt
grep -q 'REFINE_SCOPE' actions-table.txt
aie_without_git next-actions WRK-0001 --format csv > actions.csv
grep -q '^work_id,code,message,command' actions.csv
grep -q '^WRK-0001,CREATE_PLAN,' actions.csv
aie_without_git project compatibility --format json > compatibility.json
grep -q '"state" : "CURRENT"' compatibility.json
grep -q '"migrationRequired" : false' compatibility.json
@@ -164,10 +164,26 @@ public final class EngineeringCli implements Runnable {
}
@Command(name = "status", mixinStandardHelpOptions = true, description = "Inspect Works, validation and suggested next actions.")
int status(@Option(names = "--all", description = "Include archived Works.") boolean all,
@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(verification.status(root(), all), format); }
@Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) {
Path root = root();
if (format == Listing.Format.json) return emit(verification.status(root, all), Format.json);
var state = new CompatibilityService().inspect(root).summary();
var selected = works.list(root).stream().filter(w -> all || !w.archived()).toList();
if (format != Listing.Format.csv) {
String name = projects.load(root).project().name();
String details = (format == Listing.Format.markdown ? Listing.markdown(name) : Listing.singleLine(name)) + " | Onboarded: " + ProtocolGuide.installed(root)
+ " | Compatibility: " + state.state();
output.println(format == Listing.Format.markdown ? "# Project status\n\n" + details + "\n" : details + "\n");
}
output.print(Listing.works(verification.overview(root, selected), format)); return 0;
}
@Command(name = "next-actions", mixinStandardHelpOptions = true, description = "Suggest deterministic next actions; does not execute them.")
int nextActions(@Parameters(index = "0", arity = "0..1") String id,
@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(verification.nextActions(root(), id), format); }
@Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) {
var actions = verification.nextActions(root(), id);
if (format == Listing.Format.json) return emit(actions, Format.json);
output.print(Listing.actions(actions, format)); return 0;
}
@Command(name = "project", mixinStandardHelpOptions = true, description = "Inspect and validate the engineering project.")
public class ProjectCommands {
@Command(name = "compatibility", mixinStandardHelpOptions = true,
@@ -216,7 +232,13 @@ public final class EngineeringCli implements Runnable {
return emit(works.create(root(), title, description, goal, motivation, safe(constraints), safe(criteria), safe(repositories), author), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(works.list(root()), format); }
int list(@Option(names = "--open", description = "Only nonterminal, unarchived Works (OPEN, ACTIVE, BLOCKED).") boolean open,
@Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) {
Path root = root();
var selected = works.list(root).stream().filter(w -> !open || (!w.terminal() && !w.archived())).toList();
if (format == Listing.Format.json) return emit(selected, Format.json);
output.print(Listing.works(verification.overview(root, selected), format)); return 0;
}
@Command(name = "show", mixinStandardHelpOptions = true)
int show(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(works.load(root(), id), format); }
@Command(name = "update", mixinStandardHelpOptions = true, description = "Update specified Work fields, preserving history and references.")
@@ -0,0 +1,68 @@
package net.intrepid.aiengineering.cli;
import net.intrepid.aiengineering.verification.VerificationService;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/** Presentation only: no file access, transitions, or model calls. */
final class Listing {
enum Format { markdown, json, table, csv }
static String works(List<VerificationService.Overview> works, Format format) {
var rows = works.stream().map(view -> List.of(view.work().id(), view.work().title(),
view.work().status().name(), Boolean.toString(view.work().archived()), view.steps(),
Integer.toString(view.nextActions().size()), view.validation().valid() ? "valid" : "INVALID",
view.nextActions().isEmpty() ? "" : view.nextActions().getFirst().command())).toList();
return render(List.of("id", "title", "status", "archived", "steps", "pending_actions", "validation", "next_action"),
List.of("ID", "Title", "Status", "Archived", "Steps", "Pending actions", "Validation", "Next action"), rows, format);
}
static String actions(List<VerificationService.Action> actions, Format format) {
var rows = actions.stream().map(action -> List.of(action.workId() == null ? "" : action.workId(),
action.code(), action.message(), action.command())).toList();
return render(List.of("work_id", "code", "message", "command"),
List.of("Work", "Action", "Pending", "Command"), rows, format);
}
private static String render(List<String> csvHeaders, List<String> headers, List<List<String>> rows, Format format) {
if (format == Format.csv) return line(csvHeaders, Listing::csv, ",", "", "\r\n")
+ String.join("", rows.stream().map(row -> line(row, Listing::csv, ",", "", "\r\n")).toList());
if (format == Format.markdown) return line(headers, Listing::markdown, " | ", "| ", " |\n")
+ line(headers.stream().map(_ -> "---").toList(), Function.identity(), " | ", "| ", " |\n")
+ String.join("", rows.stream().map(row -> line(row, Listing::markdown, " | ", "| ", " |\n")).toList());
if (format != Format.table) throw new IllegalArgumentException("JSON listings use the full data contract");
var cells = new ArrayList<List<String>>(); cells.add(headers);
cells.addAll(rows.stream().map(row -> row.stream().map(Listing::singleLine).toList()).toList());
int[] widths = new int[headers.size()];
for (var row : cells) for (int i = 0; i < widths.length; i++) widths[i] = Math.max(widths[i], width(row.get(i)));
var result = new StringBuilder();
for (int r = 0; r < cells.size(); r++) {
var row = cells.get(r);
for (int i = 0; i < widths.length; i++) {
if (i > 0) result.append(" ");
result.append(row.get(i));
if (i < widths.length - 1) result.append(" ".repeat(widths[i] - width(row.get(i))));
}
result.append('\n');
if (r == 0) result.append(String.join(" ", java.util.Arrays.stream(widths).mapToObj(w -> "-".repeat(w)).toList())).append('\n');
}
return result.toString();
}
private static int width(String value) { return value.codePointCount(0, value.length()); }
private static String line(List<String> row, Function<String, String> escape, String separator, String prefix, String suffix) {
return prefix + String.join(separator, row.stream().map(escape).toList()) + suffix;
}
private static String csv(String value) {
return value.contains(",") || value.contains("\"") || value.contains("\r") || value.contains("\n")
? "\"" + value.replace("\"", "\"\"") + "\"" : value;
}
static String singleLine(String value) { return value.replaceAll("[\\p{Cntrl}\\p{Zl}\\p{Zp}]", " "); }
static String markdown(String value) {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\\", "&#92;").replace("|", "&#124;").replace("`", "&#96;")
.replace("*", "&#42;").replace("_", "&#95;").replace("[", "&#91;").replace("]", "&#93;")
.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "<br>").replaceAll("[\\p{Cntrl}\\p{Zl}\\p{Zp}]", " ");
}
}
@@ -270,6 +270,22 @@ public final class VerificationService {
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,
CompatibilityService.Summary compatibility) {}
/** Read-only projection for human listings; the full JSON contracts remain unchanged. */
public record Overview(Work work, String steps, ValidationReport validation, List<Action> nextActions) {}
public List<Overview> overview(Path root, List<Work> selected) {
return selected.stream().map(w -> {
var validation = work(root, w.id());
String progress = "unavailable";
try {
var steps = plans.list(root, w.id()).stream().flatMap(p -> p.steps().stream()).toList();
progress = steps.stream().filter(s -> s.status() == Plan.Status.COMPLETED).count() + "/" + steps.size();
} catch (ProtocolException failure) {
if (validation.valid()) throw failure;
// Keep repairable Works visible without claiming a zero-step plan.
}
return new Overview(w, progress, validation, actions(root, w, validation));
}).toList();
}
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(),
@@ -282,8 +298,10 @@ public final class VerificationService {
selected.forEach(w -> result.addAll(actions(root, w))); return List.copyOf(result);
}
private List<Action> actions(Path root, Work work) {
return actions(root, work, work(root, work.id()));
}
private List<Action> actions(Path root, Work work, ValidationReport validation) {
String id = work.id(); var actions = new ArrayList<Action>();
var validation = work(root, id);
if (!validation.valid()) return List.of(new Action(work.epic() ? "RECONCILE_EPIC" : "REPAIR_PROTOCOL", id,
String.join("; ", validation.issues()), work.epic() ? "aie epic reconcile " + id : "aie work validate " + id));
if (work.archived()) return List.of(new Action("REOPEN", id, "Reopen only when new work is needed", "aie work reopen " + id + " --help"));
@@ -0,0 +1,127 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.cli.EngineeringCli;
import net.intrepid.aiengineering.filesystem.Documents;
import net.intrepid.aiengineering.verification.VerificationService;
import net.intrepid.aiengineering.work.WorkService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import tools.jackson.databind.JsonNode;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import static org.assertj.core.api.Assertions.*;
class ListingTest {
@TempDir Path root;
private String output;
private int cli(String... args) {
var out = new StringWriter(); var err = new StringWriter();
int code = new EngineeringCli(root).execute(new PrintWriter(out), new PrintWriter(err), args);
output = out + err.toString(); return code;
}
private String ok(String... args) { assertThat(cli(args)).as(output).isZero(); return output; }
private JsonNode json(String text) { return Documents.parseJson(text, JsonNode.class); }
private void init() { ok("init", "--name", "List project"); }
private void create(String title) { ok("work", "create", title, "--acceptance", "Verified fixture"); }
private void evidence(String work) throws Exception {
Path result = Files.writeString(root.resolve("result.txt"), "Observed fixture result\n");
ok("artifact", "add", work, "--file", result.toString(), "--purpose", "Observed fixture");
}
private Map<String, String> snapshot() throws Exception {
var result = new TreeMap<String, String>();
try (var paths = Files.walk(root.resolve(".ai-engineering"))) {
for (var path : paths.filter(Files::isRegularFile).toList()) result.put(root.relativize(path).toString(), Files.readString(path));
}
return result;
}
@Test void summariesUseRegisteredStepsAndExistingActionsWithoutChangingJsonOrFiles() throws Exception {
init(); create("Revisão, \"CLI\" | <tag>\\path\nsegunda linha"); evidence("WRK-0001");
ok("plan", "create", "WRK-0001", "--title", "First");
for (String title : new String[]{"Done", "Blocked", "Cancelled"})
ok("plan", "step", "add", "WRK-0001", "PLN-0001", "--title", title);
ok("plan", "step", "status", "WRK-0001", "PLN-0001", "TSK-0001", "COMPLETED", "--by", "fixture",
"--reason", "Observed", "--evidence", "ART-0001");
ok("plan", "step", "status", "WRK-0001", "PLN-0001", "TSK-0002", "BLOCKED", "--by", "fixture", "--reason", "Investigate");
ok("plan", "step", "status", "WRK-0001", "PLN-0001", "TSK-0003", "CANCELLED", "--by", "fixture", "--reason", "Scope review needed");
ok("plan", "create", "WRK-0001", "--title", "Second");
ok("plan", "step", "add", "WRK-0001", "PLN-0002", "--title", "Next");
ok("discussion", "add", "WRK-0001", "--kind", "QUESTION", "--text", "Which, \"scope\"?\nFollow up | detail");
ok("decision", "draft", "WRK-0001", "--title", "Pending decision");
ok("survey", "create", "WRK-0001", "--title", "Empty survey");
var before = snapshot();
var actions = new VerificationService().nextActions(root, "WRK-0001");
for (String format : new String[]{"table", "markdown", "csv"}) {
String list = ok("work", "list", "--format", format);
assertThat(list).contains("WRK-0001", "1/4", "aie discussion add WRK-0001 --help");
String status = ok("status", "--format", format);
assertThat(status).contains(list);
String next = ok("next-actions", "WRK-0001", "--format", format);
assertThat(next.replace("&#95;", "_")).contains("RESPOND", "ADD_QUESTION", "REVIEW_DECISION", "INVESTIGATE", "EXECUTE_STEP");
}
assertThat(ok("work", "list")).startsWith("| ID | Title | Status |").contains("&#124;", "&lt;tag&gt;", "&#92;path<br>segunda linha");
assertThat(ok("work", "list", "--format", "csv")).startsWith("id,title,status,archived,steps,pending_actions,validation,next_action\r\n")
.contains("\"Revisão, \"\"CLI\"\" | <tag>\\path\nsegunda linha\",OPEN,false,1/4," + actions.size() + ",valid,");
assertThat(ok("next-actions", "WRK-0001", "--format", "csv")).contains("\"DSC-0001: Which, \"\"scope\"\"?\nFollow up | detail\"");
assertThat(ok("work", "list", "--format", "table")).doesNotContain("path\nsegunda", "<br>", "&#124;");
assertThat(ok("work", "list", "--format", "json")).isEqualTo(Documents.json(new WorkService().list(root)));
assertThat(ok("status", "--format", "json")).isEqualTo(Documents.json(new VerificationService().status(root, false)));
assertThat(ok("next-actions", "WRK-0001", "--format", "json")).isEqualTo(Documents.json(actions));
assertThat(snapshot()).isEqualTo(before);
}
@Test void openFilterIncludesOpenActiveAndBlockedAcrossFormatsAndRetainsArchiveDefaults() throws Exception {
init();
for (String title : new String[]{"Open", "Active", "Blocked", "Cancelled", "Completed", "Archived"}) create(title);
ok("work", "status", "WRK-0002", "ACTIVE"); ok("work", "status", "WRK-0003", "BLOCKED");
ok("work", "status", "WRK-0004", "CANCELLED"); ok("work", "status", "WRK-0006", "CANCELLED");
ok("work", "archive", "WRK-0006", "--by", "fixture", "--reason", "Keep history");
evidence("WRK-0005");
ok("work", "complete", "WRK-0005", "--by", "fixture-human", "--human-approved", "--summary", "Fixture reviewed",
"--criterion", "1=ART-0001", "--no-integration-needed", "Disposable fixture");
var before = snapshot();
for (String format : new String[]{"table", "markdown", "csv", "json"}) {
assertThat(ok("work", "list", "--open", "--format", format)).contains("WRK-0001", "WRK-0002", "WRK-0003")
.doesNotContain("WRK-0004", "WRK-0005", "WRK-0006");
assertThat(ok("work", "list", "--format", format)).contains("WRK-0004", "WRK-0005", "WRK-0006");
assertThat(ok("status", "--format", format)).contains("WRK-0004", "WRK-0005").doesNotContain("WRK-0006");
assertThat(ok("status", "--all", "--format", format)).contains("WRK-0006");
assertThat(ok("next-actions", "--format", format)).doesNotContain("WRK-0006");
assertThat(ok("next-actions", "WRK-0006", "--format", format)).contains("REOPEN");
}
assertThat(json(ok("work", "list", "--open", "--format", "json")).size()).isEqualTo(3);
assertThat(snapshot()).isEqualTo(before);
}
@Test void emptyListingsHaveHeadersAndUnknownFormatsFailBeforeWriting() throws Exception {
init(); var before = snapshot();
assertThat(ok("work", "list", "--open", "--format", "CSV"))
.isEqualTo("id,title,status,archived,steps,pending_actions,validation,next_action\r\n");
assertThat(ok("next-actions", "--format", "csv")).isEqualTo("work_id,code,message,command\r\n");
assertThat(ok("status", "--format", "csv")).isEqualTo("id,title,status,archived,steps,pending_actions,validation,next_action\r\n");
for (String format : new String[]{"table", "markdown"}) {
assertThat(ok("work", "list", "--open", "--format", format)).contains("ID", "Title").doesNotContain("WRK-");
assertThat(ok("next-actions", "--format", format)).contains("Work", "Command").doesNotContain("WRK-");
}
assertThat(cli("work", "list", "--format", "xml")).isEqualTo(2);
assertThat(cli("work", "show", "WRK-0001", "--format", "table")).isEqualTo(2);
assertThat(cli("next-actions", "WRK-9999", "--format", "table")).isEqualTo(3);
assertThat(snapshot()).isEqualTo(before);
}
@Test void invalidPlansStayVisibleWithRepairActionAndUnavailableProgress() throws Exception {
init(); create("Repairable"); ok("plan", "create", "WRK-0001", "--title", "Broken plan");
Path path = root.resolve(".ai-engineering/works/WRK-0001-repairable/plans/PLN-0001.md");
Files.writeString(path, "not a plan\n"); var before = snapshot();
for (String format : new String[]{"table", "markdown", "csv"}) {
assertThat(ok("work", "list", "--open", "--format", format)).contains("WRK-0001", "INVALID", "unavailable", "aie work validate WRK-0001");
assertThat(ok("status", "--format", format)).contains("INVALID", "unavailable");
assertThat(ok("next-actions", "WRK-0001", "--format", format).replace("&#95;", "_")).contains("REPAIR_PROTOCOL");
}
assertThat(snapshot()).isEqualTo(before);
}
}