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:
2026-11-11 19:50:36 +00:00
parent 8160c991a4
commit 94e3135c2e
12 changed files with 353 additions and 18 deletions
@@ -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'); }
}