feat: store discussion prose in Markdown bodies

Add versioned Markdown discussion documents with legacy YAML reading and explicit migration that backs up originals and preserves semantic history.

Render readable discussion and decision prose in Markdown context, document compatibility, and extend native smoke coverage for migration.

Validated with 29 passing tests, macOS ARM64 native smoke, and context-preserving migration of the Zelda pilot Work.
This commit is contained in:
Nilton Constantino
2026-11-11 19:50:36 +00:00
parent e65f216926
commit c84bb8d36f
12 changed files with 353 additions and 18 deletions
+18
View File
@@ -139,6 +139,24 @@ be grouped with `--discussion <name>`. History remains append-only. `work status
WRK-0001 ACTIVE` changes lifecycle status; all initial statuses are reversible.
Every command provides `--help`; inspection commands support `--format json`.
New discussion files keep metadata in YAML front matter (`documentVersion: 2`) and
the complete text in the Markdown body. Headings, lists, tables and code blocks remain
readable directly in an editor. Markdown context/list output also displays prose
directly; JSON continues to expose the same `text` field.
Older discussion files with `text` in YAML are read without being rewritten. To
convert a Work's existing discussions explicitly with the updated CLI:
```sh
ai-engineering discussion migrate WRK-0001
```
Originals are backed up under `.ai-engineering/.local/backups/discussions/`; the
command reports the backup paths. IDs, authors, dates, text, Work metadata and exported
context data are preserved. Running the command again skips converted files. Migration
refuses legacy trailing notes rather than silently dropping them. Use the updated CLI
for files in document version 2; old CLI builds cannot read that new file format.
Exit codes: **0** success, **1** unexpected I/O/runtime failure, **2** invalid input
or unsafe path, **3** missing project/resource, **4** structural validation failure.
Validation commands return 4 with diagnostics even when the underlying issue is a
+7
View File
@@ -79,6 +79,13 @@ processor provides command reflection metadata. The Spring AOT tasks are wired b
native build plugin. No application arguments are passed through Spring's property
parser. The entry point explicitly chooses non-web mode and closes its context.
Discussion document version 2 separates typed YAML metadata from an opaque Markdown
body. The filesystem codec maps that body to the domain record's existing `text`
field; it does not infer structure from prose headings. The reader accepts legacy
YAML-only text as well. Explicit migration backs up originals, preserves semantic
state and skips converted files. Work and draft DEC persistence are unchanged;
Markdown context renders discussion/decision prose without YAML escaping.
## Earlier framework review and migration
Both implementations were inspected read-only:
+30
View File
@@ -157,6 +157,36 @@ Native compilation succeeded on macOS ARM64. With `JAVA_HOME` and `GRAALVM_HOME`
pointing to nonexistent paths, the expanded smoke passed both the simple-project
scenarios (including no Git on PATH) and the multi-repository scenario.
## H6 — Discussion readability and compatible migration
The Zelda pilot produced a long suggestion whose YAML string was hard to inspect in
an editor. New discussions now store metadata in front matter with `documentVersion: 2`
and canonical prose in the Markdown body. Context and discussion-list Markdown output
render prose directly. Work/draft DEC storage and JSON record fields are unchanged.
Six new tests verify exact Unicode/Markdown/whitespace round trips, legacy read-only
loading, context-preserving migration and backups, idempotence, refusal of legacy
trailing notes, ambiguous/unknown formats, and CRLF front matter. The complete suite
passed with **29 tests, 0 failures, 0 errors, 0 skipped**, including Modulith.
A copy of the actual Zelda Work was staged at
`/tmp/aie-zelda-markdown-preview.z3YttK`. Both legacy discussion entries converted
successfully, with originals backed up. JSON and Markdown contexts before/after
migration compared byte-for-byte equal. The long `DSC-0002` proposal can now be read
directly as ordinary paragraphs and lists, without escaped newlines or split words.
The source project was not modified during this rehearsal.
The native smoke additionally constructs a legacy entry, migrates it, verifies the
new format, repeats migration to confirm no-op behavior, and compares exported context.
The complete native smoke passed on macOS ARM64, including migration without Git
on PATH and the existing single-/multi-repository layouts. The converted Zelda copy
also validated with the native binary; repeating migration reported zero conversions.
After the rehearsal, both discussions in the original Zelda Work were explicitly
migrated with the native CLI. Original files were retained under the reported `.local`
backup directory. JSON context, Markdown context and `work.md` compared byte-for-byte
equal before/after conversion; project validation returned `valid: true`, no issues.
## Limits and next experiment
CI workflows are provided but have not been executed from this local workspace.
+54 -4
View File
@@ -77,10 +77,10 @@ processes. The adapter clears inherited `GIT_*` variables and disables optional
```
`work.md`, discussion and decision files contain YAML front matter, delimited by
`---`. All semantic content lives in the front matter in this version; trailing
Markdown is reserved for noncanonical notes and is not exported. YAML multiline strings
remain human-readable. Edit the typed fields to update canonical content. There is no
Java object serialization and no dependency on conversation state.
`---`. Work and draft DEC files retain their typed fields in front matter; trailing
Markdown in those documents remains noncanonical. Discussion files use the Markdown
body for prose as described below. There is no Java object serialization and no
dependency on conversation state.
Work fields: `schemaVersion`, `id`, `title`, `description`, `goal`, `motivation`,
`constraints[]`, `acceptanceCriteria[]`, `status`, `createdAt`, `updatedAt`, `author`,
@@ -108,6 +108,51 @@ coexist. Kinds: NOTE, QUESTION, RESPONSE, SUGGESTION, ASSUMPTION, HYPOTHESIS,
INVESTIGATION, ALTERNATIVE, ISSUE, CONCLUSION. Entries are appended, not rewritten.
Text is supplied by a human or external agent; the CLI never fabricates conclusions.
New discussion files have `documentVersion: 2` in front matter and omit the `text`
field there. The complete Markdown body supplies `text`, including its original
headings, lists, tables, code blocks and whitespace:
```markdown
---
schemaVersion: 1
id: DSC-0002
workId: WRK-0001
discussionId: main
kind: SUGGESTION
author: agent
createdAt: '2026-11-11T16:47:32Z'
respondsTo: DSC-0001
documentVersion: 2
---
## Proposed approach
Use the next small, testable slice.
- State the limits.
- Identify supporting evidence.
```
One blank line separates the closing delimiter from the body; that formatting line
is excluded from `text`. All subsequent whitespace belongs to the prose. LF and CRLF
front matter are accepted; the reader does not normalize the body's line endings.
`schemaVersion: 1` still describes the protocol record. `documentVersion: 2` describes
this file representation, not a change to JSON context fields. Unknown document
versions and simultaneous YAML `text` plus a version 2 body fail validation.
Legacy discussions omit `documentVersion` (or declare 1) and keep canonical `text`
in YAML; their trailing body remains noncanonical notes. The new reader accepts both
representations without automatic writes. The old CLI cannot read document version 2.
`discussion migrate <Work>` explicitly converts legacy entries. Every discussion is
preflighted before any file is replaced. Nonblank legacy trailing notes cause refusal;
incorporate those notes into canonical text first. Original UTF-8 files are backed up
under `.local/backups/discussions/<Work>/<operation-id>/` before atomic replacement.
Migration preserves all semantic fields, Work timestamps and context JSON/Markdown,
and skips already converted entries. It changes formatting, not discussion history.
Interrupted migrations can be resumed; completed files are skipped and existing backups
are retained. This is per-file publication, not an all-or-nothing multi-file transaction.
A response must refer to an earlier entry in the same Work. Outstanding questions
include QUESTION and ISSUE entries without an explicit RESPONSE or CONCLUSION pointing
to them. This mechanical definition does not infer agreement or approval from prose.
@@ -148,6 +193,11 @@ files yield byte-identical output across new instances and processes. Export rej
broken references or integrity failures. It requires neither a model nor live Git
inspection; `project validate` separately verifies live repositories.
Markdown context renders discussion and decision prose directly, with IDs, authors,
timestamps and reply/approval metadata. Empty sections use `None recorded.`. JSON
keeps the complete typed records, including discussion `text`, regardless of their
on-disk document version. Evidence remains referenced rather than embedded.
## Write guarantees and recovery
Protocol mutations hold `.local/write.lock`, an OS lock released automatically at
+14
View File
@@ -30,7 +30,21 @@ aie_without_git work create 'Continue application' --goal 'Preserve local contex
aie_without_git discussion add WRK-0001 --text 'No repository is required' > discussion.yaml
aie_without_git artifact add WRK-0001 --file main.txt --purpose 'Initial source evidence' > artifact.yaml
aie_without_git decision draft WRK-0001 --title 'Pilot the protocol' --evidence ART-0001 > decision.yaml
# Exercise compatibility/migration using an exact legacy representation of this entry.
aie_discussion=.ai-engineering/works/WRK-0001-continue-application/discussions/DSC-0001.md
grep -q 'documentVersion: 2' "$aie_discussion"
awk '
/^---$/ { delimiters++; if (delimiters == 2) { print "text: \"No repository is required\""; print "---"; exit } }
/documentVersion:/ { next }
{ print }
' "$aie_discussion" > legacy.md
cp legacy.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
grep -q 'documentVersion: 2' "$aie_discussion"
aie_without_git discussion migrate WRK-0001 --format json > repeated-migration.json
grep -q '"converted" : 0' repeated-migration.json
mkdir src
cd src
aie_without_git work context WRK-0001 --format json > ../after.json
@@ -12,7 +12,7 @@ public final class NativeHints implements RuntimeHintsRegistrar {
@Override public void registerHints(RuntimeHints hints, ClassLoader loader) {
for (Class<?> type : new Class<?>[]{ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class,
ProjectConfig.Access.class, ProjectService.Revision.class, Work.class, WorkService.Sequence.class, DiscussionEntry.class,
DraftDecision.class, Artifact.class, ValidationReport.class, VerificationService.Context.class}) {
DraftDecision.class, Artifact.class, ValidationReport.class, VerificationService.Context.class, DiscussionService.MigrationReport.class}) {
hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
}
}
@@ -115,11 +115,19 @@ public final class EngineeringCli implements Runnable {
@Option(names = "--author", defaultValue = "human") String author,
@Option(names = "--discussion", defaultValue = "main") String thread,
@Option(names = "--responds-to") String respondsTo) {
return emit(new DiscussionService().add(root(), id, text, kind, author, thread, respondsTo), Format.markdown);
var entry = new DiscussionService().add(root(), id, text, kind, author, thread, respondsTo);
output.print(Documents.markdownDocument(entry, "text")); return 0;
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
return emit(new DiscussionService().list(root(), id), format);
var entries = new DiscussionService().list(root(), id);
if (format == Format.json) return emit(entries, format);
output.println(verification.discussionMarkdown(entries)); return 0;
}
@Command(name = "migrate", mixinStandardHelpOptions = true,
description = "Convert legacy discussion prose to Markdown bodies, backing up originals in .local.")
int migrate(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
return emit(new DiscussionService().migrate(root(), id), format);
}
}
@Command(name = "decision", mixinStandardHelpOptions = true, description = "Persist draft formal decisions.")
@@ -11,7 +11,7 @@ public final class DiscussionService {
public List<DiscussionEntry> list(Path root, String id) {
Work work = works.load(root, id); Path folder = works.folder(root, id);
return work.discussions().stream().map(ref -> {
var entry = Documents.readDocument(Filespace.resolve(folder, "discussions/" + ref + ".md"), DiscussionEntry.class);
var entry = Documents.readMarkdownDocument(Filespace.resolve(folder, "discussions/" + ref + ".md"), DiscussionEntry.class, "text");
if (!entry.id().equals(ref) || !entry.workId().equals(id)) throw ProtocolException.validation("Discussion identity mismatch: " + ref);
return entry;
}).toList();
@@ -23,8 +23,41 @@ public final class DiscussionService {
throw ProtocolException.invalid("Response target not found in Work: " + respondsTo);
String id = works.nextReference(work.discussions(), "DSC");
var entry = new DiscussionEntry(1, id, workId, discussionId, kind, author, Instant.now().toString(), respondsTo, text);
Documents.writeDocument(Filespace.resolve(works.folder(root, workId), "discussions/" + id + ".md"), entry, false);
Documents.writeMarkdownDocument(Filespace.resolve(works.folder(root, workId), "discussions/" + id + ".md"), entry, "text", false);
works.addReference(root, workId, "discussions", id); return entry;
});
}
public record MigrationReport(int schemaVersion, int converted, int unchanged, List<String> backups) {
public MigrationReport { backups = List.copyOf(backups); }
}
private record Conversion(Path path, String original, String converted) {}
/** Explicit formatting migration, preserving semantic history and Work modification timestamps. */
public MigrationReport migrate(Path root, String workId) {
return Filespace.locked(root, () -> {
var entries = list(root, workId); var conversions = new java.util.ArrayList<Conversion>();
Path folder = works.folder(root, workId);
// Preflight every entry before creating backups or replacing any file.
for (var entry : entries) {
Path path = Filespace.resolve(folder, "discussions/" + entry.id() + ".md");
if (Documents.documentVersion(path) == 1) {
String original = Filespace.read(path);
if (!Documents.readMarkdownDocument(path, DiscussionEntry.class, "text").equals(entry))
throw ProtocolException.validation("Discussion changed during migration: " + path);
conversions.add(new Conversion(path, original, Documents.markdownMigration(path, entry, "text")));
}
}
var backups = new java.util.ArrayList<String>();
String backupDirectory = ".ai-engineering/.local/backups/discussions/" + workId + "/" + java.util.UUID.randomUUID();
for (var conversion : conversions) {
if (!Filespace.read(conversion.path()).equals(conversion.original()))
throw ProtocolException.validation("Discussion changed during migration; retry after the other editor finishes: " + conversion.path());
String relative = backupDirectory + "/" + conversion.path().getFileName();
Path backup = Filespace.resolve(root, relative); Filespace.directory(backup.getParent());
Filespace.write(backup, conversion.original(), false);
Filespace.write(conversion.path(), conversion.converted(), true);
backups.add(relative);
}
return new MigrationReport(1, conversions.size(), entries.size() - conversions.size(), backups);
});
}
}
@@ -5,7 +5,9 @@ import tools.jackson.dataformat.yaml.YAMLMapper;
import tools.jackson.core.StreamReadFeature;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.cfg.EnumFeature;
import tools.jackson.databind.node.ObjectNode;
import java.nio.file.Path;
import java.util.regex.Pattern;
/** Explicit protocol records, never Spring internal objects, are canonical. */
public final class Documents {
@@ -13,6 +15,7 @@ public final class Documents {
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
DeserializationFeature.FAIL_ON_TRAILING_TOKENS).enable(EnumFeature.FAIL_ON_NUMBERS_FOR_ENUMS).build();
private static final JsonMapper JSON = JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build();
private static final Pattern FRONT_MATTER = Pattern.compile("\\A---\\r?\\n(.*?)\\r?\\n---(?:\\r?\\n|\\z)", Pattern.DOTALL);
private Documents() {}
public static String yaml(Object value) { return YAML.writeValueAsString(value); }
public static String json(Object value) { return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value) + "\n"; }
@@ -22,11 +25,59 @@ public final class Documents {
}
public static <T> T read(Path path, Class<T> type) { return parse(Filespace.read(path), type); }
public static <T> T readDocument(Path path, Class<T> type) {
String text = Filespace.read(path);
if (!text.startsWith("---\n")) throw ProtocolException.validation("Missing YAML front matter: " + path);
int end = text.indexOf("\n---\n", 4);
if (end < 0) throw ProtocolException.validation("Unclosed YAML front matter: " + path);
return parse(text.substring(4, end), type);
return readMarkdownDocument(path, type, null);
}
/** Version 1 keeps prose in YAML; version 2 maps the Markdown body to one explicit text field. */
public static <T> T readMarkdownDocument(Path path, Class<T> type, String bodyField) {
var parts = parts(path);
int version = version(parts.metadata(), path);
parts.metadata().remove("documentVersion");
if (version == 2) {
if (bodyField == null) throw ProtocolException.validation("Markdown body is not supported for " + type.getSimpleName());
if (parts.metadata().has(bodyField)) throw ProtocolException.validation("Ambiguous " + bodyField + " in front matter and Markdown body: " + path);
String body = parts.body();
if (body.startsWith("\r\n")) body = body.substring(2);
else if (body.startsWith("\n")) body = body.substring(1);
else throw ProtocolException.validation("Expected a blank line after front matter: " + path);
parts.metadata().put(bodyField, body);
}
try { return YAML.treeToValue(parts.metadata(), type); }
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); }
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();
throw ProtocolException.validation("Unsupported documentVersion at " + path + ": " + value);
}
private record Parts(ObjectNode metadata, String body) {}
private static Parts parts(Path path) {
String text = Filespace.read(path); var match = FRONT_MATTER.matcher(text);
if (!match.find()) throw ProtocolException.validation("Missing or unclosed YAML front matter: " + path);
try {
if (!(YAML.readTree(match.group(1)) instanceof ObjectNode metadata))
throw ProtocolException.validation("Front matter must be an object: " + path);
return new Parts(metadata, text.substring(match.end()));
} catch (ProtocolException e) { throw e; }
catch (RuntimeException e) { throw ProtocolException.validation("Invalid front matter at " + path + ": " + e.getMessage()); }
}
public static String markdownDocument(Object value, String bodyField) {
ObjectNode metadata = YAML.valueToTree(value);
var body = metadata.remove(bodyField);
if (body == null || !body.isString()) throw ProtocolException.invalid("Markdown body field must be text: " + bodyField);
metadata.put("documentVersion", 2);
return "---\n" + yaml(metadata).replaceFirst("^---\\n", "") + "---\n\n" + body.stringValue();
}
public static void writeMarkdownDocument(Path path, Object value, String bodyField, boolean replace) {
Filespace.write(path, markdownDocument(value, bodyField), replace);
}
public static String markdownMigration(Path path, Object value, String bodyField) {
var parts = parts(path);
if (version(parts.metadata(), path) != 1) throw ProtocolException.invalid("Document is already Markdown: " + path);
if (!parts.body().isBlank()) throw ProtocolException.validation("Legacy document has trailing notes; incorporate them into its text before migration: " + path);
return markdownDocument(value, bodyField);
}
public static void writeDocument(Path path, Object value, boolean replace) {
String yaml = yaml(value).replaceFirst("^---\\n", "");
@@ -88,14 +88,48 @@ public final class VerificationService {
section(result, "Goal", w.goal()); section(result, "Description", w.description()); section(result, "Motivation", w.motivation());
section(result, "Constraints", items(w.constraints())); section(result, "Acceptance criteria", items(w.acceptanceCriteria()));
section(result, "Repository revisions at Work creation", yaml(w.repositories()));
section(result, "Discussion history and conclusions", yaml(context.discussionHistory()));
section(result, "Decisions (approval status is explicit)", yaml(context.decisions()));
section(result, "Discussion history and conclusions", discussionMarkdown(context.discussionHistory()));
section(result, "Decisions (approval status is explicit)", decisionMarkdown(context.decisions()));
section(result, "Outstanding questions", items(context.outstandingQuestions()));
section(result, "Artifact references (paths relative to Work)", yaml(context.artifacts()));
section(result, "Metadata", "Created: " + w.createdAt() + "\n\nUpdated: " + w.updatedAt() + "\n\nAuthor: " + w.author());
return result.toString();
}
public String discussionMarkdown(List<DiscussionEntry> entries) {
if (entries.isEmpty()) return "None recorded.";
var out = new StringBuilder();
for (var entry : entries) {
if (!out.isEmpty()) out.append('\n');
out.append("### ").append(entry.id()).append(" — ").append(entry.kind()).append("\n\n")
.append("Author: ").append(entry.author()).append("\n\nThread: ").append(entry.discussionId())
.append("\n\nCreated: ").append(entry.createdAt()).append('\n');
if (entry.respondsTo() != null) out.append("\nResponds to: ").append(entry.respondsTo()).append('\n');
out.append('\n').append(entry.text()).append('\n');
}
return out.toString();
}
private static String decisionMarkdown(List<DraftDecision> decisions) {
if (decisions.isEmpty()) return "None recorded.";
var out = new StringBuilder();
for (var decision : decisions) {
if (!out.isEmpty()) out.append('\n');
out.append("### ").append(decision.id()).append(" — ").append(decision.title()).append("\n\n")
.append("Approval: ").append(decision.approvalStatus()).append("\n\nAuthor: ").append(decision.author())
.append("\n\nCreated: ").append(decision.createdAt()).append('\n');
subsection(out, "Context", decision.context()); subsection(out, "Approach", decision.approach());
subsection(out, "Alternatives", items(decision.alternatives())); subsection(out, "Rationale", decision.rationale());
subsection(out, "Risks", items(decision.risks())); subsection(out, "Acceptance criteria", items(decision.acceptanceCriteria()));
subsection(out, "Evidence", items(decision.evidence()));
}
return out.toString();
}
private static void subsection(StringBuilder out, String title, String text) {
out.append("\n#### ").append(title).append("\n\n").append(text.isBlank() ? "None recorded." : text).append('\n');
}
private static String items(List<String> values) { return values.isEmpty() ? "None recorded." : String.join("\n", values.stream().map(v -> "- " + v).toList()); }
private static String yaml(Object value) { return "```yaml\n" + Documents.yaml(value) + "```"; }
private static String yaml(Object value) {
if (value instanceof List<?> list && list.isEmpty()) return "None recorded.";
return "```yaml\n" + Documents.yaml(value) + "```";
}
private static void section(StringBuilder out, String title, String body) { out.append("\n## ").append(title).append("\n\n").append(body.isBlank() ? "None recorded." : body).append('\n'); }
}
@@ -0,0 +1,90 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.ProjectService;
import net.intrepid.aiengineering.work.WorkService;
import net.intrepid.aiengineering.verification.VerificationService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
class DiscussionMarkdownTest {
@TempDir Path root;
private final DiscussionService discussions = new DiscussionService();
private final WorkService works = new WorkService();
private void initialize() {
new ProjectService().initialize(root, "Test");
works.create(root, "One", "", "Goal", "", List.of(), List.of(), List.of(), "human");
}
private DiscussionEntry add(String text) {
return discussions.add(root, "WRK-0001", text, DiscussionEntry.Kind.SUGGESTION, "agent", "main", null);
}
private Path path(String id) { return works.folder(root, "WRK-0001").resolve("discussions/" + id + ".md"); }
@Test void newDiscussionPersistsMarkdownProseOutsideFrontMatterAndReloadsExactly() throws Exception {
initialize();
String prose = "\n## Proposta — próxima etapa\n\n- Evidência: árvore\n- 日本語\n\n```yaml\n---\nname: Zelda\n```\n\nÚltima linha sem newline";
var entry = add(prose); String stored = Files.readString(path(entry.id()));
assertThat(stored).contains("documentVersion: 2", "\n---\n\n" + prose).doesNotContain("\ntext:", "\\n");
assertThat(new DiscussionService().list(root, "WRK-0001")).containsExactly(entry);
var context = new VerificationService().context(root, "WRK-0001");
assertThat(new VerificationService().markdown(context)).contains(prose, "### DSC-0001", "SUGGESTION").doesNotContain("text:", "\\n");
assertThat(context.discussionHistory().getFirst().text()).isEqualTo(prose);
}
@Test void legacyYamlRemainsReadableWithoutImplicitWrites() throws Exception {
initialize(); var entry = add("Legacy\n\nLong text.");
String legacy = "---\n" + Documents.yaml(entry).replaceFirst("^---\\n", "") + "---\n";
Files.writeString(path(entry.id()), legacy);
assertThat(new DiscussionService().list(root, "WRK-0001")).containsExactly(entry);
assertThat(Files.readString(path(entry.id()))).isEqualTo(legacy);
}
@Test void explicitMigrationBacksUpOriginalsAndPreservesContextAndWorkMetadata() throws Exception {
initialize(); var one = add("## Long proposal\n\nA → B\n"); var two = add("Second entry");
String oldOne = legacy(one); String oldTwo = legacy(two);
Files.writeString(path(one.id()), oldOne); Files.writeString(path(two.id()), oldTwo);
String contextBefore = Documents.json(new VerificationService().context(root, "WRK-0001"));
String markdownBefore = new VerificationService().markdown(new VerificationService().context(root, "WRK-0001"));
Path work = works.folder(root, "WRK-0001").resolve("work.md"); byte[] before = Files.readAllBytes(work);
var report = discussions.migrate(root, "WRK-0001");
assertThat(report.converted()).isEqualTo(2); assertThat(report.unchanged()).isZero();
assertThat(report.backups()).hasSize(2);
assertThat(Files.readString(root.resolve(report.backups().getFirst()))).isEqualTo(oldOne);
assertThat(Files.readString(root.resolve(report.backups().getLast()))).isEqualTo(oldTwo);
assertThat(Documents.json(new VerificationService().context(root, "WRK-0001"))).isEqualTo(contextBefore);
assertThat(new VerificationService().markdown(new VerificationService().context(root, "WRK-0001"))).isEqualTo(markdownBefore);
assertThat(Files.readAllBytes(work)).isEqualTo(before);
String converted = Files.readString(path(one.id()));
var repeated = discussions.migrate(root, "WRK-0001");
assertThat(repeated.converted()).isZero(); assertThat(repeated.unchanged()).isEqualTo(2); assertThat(repeated.backups()).isEmpty();
assertThat(Files.readString(path(one.id()))).isEqualTo(converted);
}
@Test void migrationRefusesLegacyTrailingNotesBeforeChangingAnyFiles() throws Exception {
initialize(); var one = add("One"); var two = add("Two");
String oldOne = legacy(one); String oldTwo = legacy(two) + "\nUser notes that must not disappear\n";
Files.writeString(path(one.id()), oldOne); Files.writeString(path(two.id()), oldTwo);
assertThatThrownBy(() -> discussions.migrate(root, "WRK-0001")).isInstanceOf(ProtocolException.class).hasMessageContaining("trailing notes");
assertThat(Files.readString(path(one.id()))).isEqualTo(oldOne);
assertThat(Files.readString(path(two.id()))).isEqualTo(oldTwo);
assertThat(Files.exists(root.resolve(".ai-engineering/.local/backups"))).isFalse();
}
@Test void conflictingBodySourcesAndUnknownDocumentVersionsAreRejected() throws Exception {
initialize(); var entry = add("Canonical body"); String valid = Files.readString(path(entry.id()));
for (String invalid : List.of(valid.replace("documentVersion: 2", "documentVersion: 99"),
valid.replace("documentVersion: 2", "documentVersion: \"2\""),
valid.replace("documentVersion: 2", "documentVersion: 2\ntext: ambiguous"),
valid.replace("documentVersion: 2", "documentVersion: 2\nunknownField: true"))) {
Files.writeString(path(entry.id()), invalid);
assertThat(new VerificationService().work(root, "WRK-0001").valid()).isFalse();
}
}
@Test void crlfFrontMatterPreservesBodyBytesIncludingTrailingNewlines() throws Exception {
initialize(); String prose = "## Proposal\r\n\r\nKeep original line endings.\r\n"; var entry = add(prose);
String stored = Files.readString(path(entry.id())); int boundary = stored.indexOf("\n---\n");
String windows = stored.substring(0, boundary + 5).replace("\n", "\r\n") + stored.substring(boundary + 5);
Files.writeString(path(entry.id()), windows);
assertThat(new DiscussionService().list(root, "WRK-0001")).containsExactly(entry);
}
private String legacy(DiscussionEntry entry) { return "---\n" + Documents.yaml(entry).replaceFirst("^---\\n", "") + "---\n"; }
}
@@ -104,7 +104,7 @@ class ProtocolIntegrationTest {
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",
"work", "work create", "work list", "work show", "work validate", "work context", "discussion", "discussion add",
"decision", "decision draft", "artifact", "artifact add"}) {
"discussion list", "discussion migrate", "decision", "decision draft", "artifact", "artifact add"}) {
var args = new java.util.ArrayList<String>();
if (!command.isEmpty()) args.addAll(java.util.List.of(command.split(" ")));
args.add("--help"); assertThat(ok(args.toArray(String[]::new)).out()).contains("Usage:");