feat: bootstrap portable engineering protocol CLI
Implement milestones 0 and 1 with project and repository configuration, Work persistence, discussions, draft decisions, evidence integrity, and deterministic context exports. Add Java 25, Spring Boot and Modulith, native distributions, CI workflows, protocol documentation, and the pinned SDKMAN GraalVM CE toolchain. Validated with 20 passing tests and the macOS ARM64 native multi-repository continuity smoke.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package net.intrepid.aiengineering;
|
||||
|
||||
import net.intrepid.aiengineering.cli.EngineeringCli;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ImportRuntimeHints;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@SpringBootApplication(proxyBeanMethods = false)
|
||||
@ImportRuntimeHints(NativeHints.class)
|
||||
public class AiEngineeringApplication {
|
||||
@Bean EngineeringCli engineeringCli() { return new EngineeringCli(Path.of("")); }
|
||||
public static void main(String[] args) {
|
||||
var application = new SpringApplication(AiEngineeringApplication.class);
|
||||
application.setWebApplicationType(WebApplicationType.NONE);
|
||||
int exit;
|
||||
// Picocli owns argument parsing; passing user arguments to Spring could change application policy.
|
||||
try (var context = application.run()) {
|
||||
exit = context.getBean(EngineeringCli.class).execute(new PrintWriter(System.out, true), new PrintWriter(System.err, true), args);
|
||||
}
|
||||
System.exit(exit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.intrepid.aiengineering;
|
||||
|
||||
import net.intrepid.aiengineering.project.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import net.intrepid.aiengineering.discussion.*;
|
||||
import net.intrepid.aiengineering.decision.*;
|
||||
import net.intrepid.aiengineering.artifact.*;
|
||||
import net.intrepid.aiengineering.verification.*;
|
||||
import org.springframework.aot.hint.*;
|
||||
|
||||
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}) {
|
||||
hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import net.intrepid.aiengineering.work.Work;
|
||||
import java.time.Instant;
|
||||
|
||||
public record Artifact(int schemaVersion, String id, String workId, String origin, String purpose, String path,
|
||||
String sha256, long size, String author, String createdAt) {
|
||||
public Artifact {
|
||||
ProtocolException.schema(schemaVersion); Work.identifier(id, "ART"); Work.identifier(workId, "WRK");
|
||||
ProtocolException.text(origin, "origin"); ProtocolException.text(purpose, "purpose");
|
||||
ProtocolException.text(path, "artifact path"); ProtocolException.text(author, "author"); Instant.parse(createdAt);
|
||||
if (sha256 == null || !sha256.matches("[a-f0-9]{64}") || size < 0) throw ProtocolException.validation("Invalid artifact integrity metadata");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
public final class ArtifactService {
|
||||
public static final long MAX_BYTES = 1024 * 1024;
|
||||
private final WorkService works = new WorkService();
|
||||
public List<Artifact> list(Path root, String id) {
|
||||
var work = works.load(root, id); Path folder = works.folder(root, id);
|
||||
return work.artifacts().stream().map(ref -> {
|
||||
var artifact = Documents.read(Filespace.resolve(folder, "artifacts/evidence/" + ref + "/artifact.yaml"), Artifact.class);
|
||||
if (!artifact.id().equals(ref) || !artifact.workId().equals(id)) throw ProtocolException.validation("Artifact identity mismatch: " + ref);
|
||||
String expected = "artifacts/evidence/" + ref + "/payload";
|
||||
if (!artifact.path().equals(expected)) throw ProtocolException.validation("Invalid artifact payload reference: " + artifact.path());
|
||||
return artifact;
|
||||
}).toList();
|
||||
}
|
||||
public Artifact attach(Path root, String workId, Path source, String purpose, String origin, String author) {
|
||||
if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.missing("Evidence source is not a regular file: " + source);
|
||||
if (Filespace.io(() -> Files.size(source)) > MAX_BYTES) throw ProtocolException.invalid("Evidence exceeds 1 MiB; reference large resources instead");
|
||||
byte[] bytes = Filespace.io(() -> {
|
||||
try (var input = Files.newInputStream(source)) { return input.readNBytes((int) MAX_BYTES + 1); }
|
||||
});
|
||||
if (bytes.length > MAX_BYTES) throw ProtocolException.invalid("Evidence exceeds 1 MiB");
|
||||
return Filespace.locked(root, () -> {
|
||||
var work = works.load(root, workId); String id = works.nextReference(work.artifacts(), "ART");
|
||||
Path folder = works.folder(root, workId);
|
||||
Path parent = Filespace.resolve(folder, "artifacts/evidence");
|
||||
Path stage = Filespace.resolve(parent, "." + id + "-" + UUID.randomUUID() + ".tmp"); Filespace.directory(stage);
|
||||
var artifact = new Artifact(1, id, workId, origin == null ? source.getFileName().toString() : origin, purpose,
|
||||
"artifacts/evidence/" + id + "/payload", hash(bytes), bytes.length, author, Instant.now().toString());
|
||||
Filespace.writeBytes(stage.resolve("payload"), bytes, false);
|
||||
Filespace.write(stage.resolve("artifact.yaml"), Documents.yaml(artifact), false);
|
||||
Filespace.moveDirectory(stage, Filespace.resolve(parent, id));
|
||||
works.addReference(root, workId, "artifacts", id); return artifact;
|
||||
});
|
||||
}
|
||||
public void validate(Path root, String id) {
|
||||
for (var artifact : list(root, id)) {
|
||||
Path path = Filespace.resolve(works.folder(root, id), artifact.path());
|
||||
if (!Files.isRegularFile(path)) throw ProtocolException.validation("Missing artifact payload: " + artifact.path());
|
||||
if (Filespace.io(() -> Files.size(path)) != artifact.size() || artifact.size() > MAX_BYTES)
|
||||
throw ProtocolException.validation("Artifact size mismatch: " + artifact.id());
|
||||
if (!hash(Filespace.io(() -> Files.readAllBytes(path))).equals(artifact.sha256()))
|
||||
throw ProtocolException.validation("Artifact SHA-256 mismatch: " + artifact.id());
|
||||
}
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (java.security.NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
@@ -0,0 +1,150 @@
|
||||
package net.intrepid.aiengineering.cli;
|
||||
|
||||
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.*;
|
||||
import net.intrepid.aiengineering.artifact.*;
|
||||
import net.intrepid.aiengineering.verification.*;
|
||||
import picocli.CommandLine;
|
||||
import picocli.CommandLine.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Path;
|
||||
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")
|
||||
public final class EngineeringCli implements Runnable {
|
||||
private final Path cwd;
|
||||
private final ProjectService projects = new ProjectService();
|
||||
private final WorkService works = new WorkService();
|
||||
private final VerificationService verification = new VerificationService();
|
||||
private PrintWriter output;
|
||||
private CommandLine commandLine;
|
||||
@Option(names = "--project", scope = ScopeType.INHERIT, description = "Engineering project root or .ai-engineering directory.") Path project;
|
||||
public EngineeringCli(Path cwd) { this.cwd = cwd.toAbsolutePath().normalize(); }
|
||||
public int execute(PrintWriter out, PrintWriter err, String... args) {
|
||||
output = out;
|
||||
commandLine = new CommandLine(this)
|
||||
.addSubcommand("project", new ProjectCommands()).addSubcommand("repo", new RepoCommands())
|
||||
.addSubcommand("work", new WorkCommands()).addSubcommand("discussion", new DiscussionCommands())
|
||||
.addSubcommand("decision", new DecisionCommands()).addSubcommand("artifact", new ArtifactCommands());
|
||||
configure(commandLine, out, err);
|
||||
commandLine.setExecutionExceptionHandler((exception, command, parse) -> {
|
||||
if (exception instanceof ProtocolException problem) { err.println(problem.getMessage()); return problem.exitCode(); }
|
||||
if (exception instanceof IllegalArgumentException) { err.println("Invalid input: " + exception.getMessage()); return 2; }
|
||||
err.println("Operation failed: " + exception.getMessage()); return 1;
|
||||
});
|
||||
int result = commandLine.execute(args); out.flush(); err.flush(); return result;
|
||||
}
|
||||
private void configure(CommandLine command, PrintWriter out, PrintWriter err) {
|
||||
command.setOut(out).setErr(err).setCaseInsensitiveEnumValuesAllowed(true);
|
||||
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 resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); }
|
||||
enum Format { markdown, json }
|
||||
private int emit(Object value, Format format) {
|
||||
output.print(format == Format.json ? Documents.json(value) : Documents.yaml(value)); return 0;
|
||||
}
|
||||
private int report(ValidationReport report, Format format) { emit(report, format); return report.valid() ? 0 : 4; }
|
||||
|
||||
@Command(name = "init", mixinStandardHelpOptions = true, description = "Initialize protocol files without modifying Git.")
|
||||
int init(@Option(names = "--name", required = true) String name) {
|
||||
Path target = project == null ? cwd : resolve(project);
|
||||
return emit(projects.initialize(target, name), Format.markdown);
|
||||
}
|
||||
@Command(name = "project", mixinStandardHelpOptions = true, description = "Inspect and validate the engineering project.")
|
||||
public class ProjectCommands {
|
||||
@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)
|
||||
int validate(@Option(names = "--format", defaultValue = "markdown") Format format) { return report(verification.project(root()), format); }
|
||||
}
|
||||
@Command(name = "repo", mixinStandardHelpOptions = true, description = "Register existing source repositories; default access is read-only.")
|
||||
public class RepoCommands {
|
||||
@Command(name = "add", mixinStandardHelpOptions = true)
|
||||
int add(@Parameters(index = "0") String id, @Option(names = "--path", required = true) String path,
|
||||
@Option(names = "--type", defaultValue = "linked-git") String type,
|
||||
@Option(names = "--language") String language, @Option(names = "--allow-edit") boolean edit,
|
||||
@Option(names = "--validation-command") List<String> commands) {
|
||||
var repo = new ProjectConfig.Repository(id, path, type, language, new ProjectConfig.Access(true, edit), commands);
|
||||
return emit(projects.addRepository(root(), repo), Format.markdown);
|
||||
}
|
||||
@Command(name = "list", mixinStandardHelpOptions = true)
|
||||
int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()).repositories(), format); }
|
||||
}
|
||||
@Command(name = "work", mixinStandardHelpOptions = true, description = "Create, inspect, validate and export Works.")
|
||||
public class WorkCommands {
|
||||
@Command(name = "create", mixinStandardHelpOptions = true)
|
||||
int create(@Parameters(index = "0") String title,
|
||||
@Option(names = "--description", defaultValue = "") String description,
|
||||
@Option(names = "--goal", defaultValue = "") String goal,
|
||||
@Option(names = "--motivation", defaultValue = "") String motivation,
|
||||
@Option(names = "--constraint") List<String> constraints,
|
||||
@Option(names = "--acceptance") List<String> criteria,
|
||||
@Option(names = "--repo") List<String> repositories,
|
||||
@Option(names = "--author", defaultValue = "human") String author) {
|
||||
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); }
|
||||
@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 = "validate", mixinStandardHelpOptions = true)
|
||||
int validate(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
Work.identifier(id, "WRK"); Path root = root(); works.load(root, id); return report(verification.work(root, id), format);
|
||||
}
|
||||
@Command(name = "context", mixinStandardHelpOptions = true)
|
||||
int context(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
Work.identifier(id, "WRK"); Path root = root(); works.load(root, id);
|
||||
var context = verification.context(root, id);
|
||||
output.print(format == Format.json ? Documents.json(context) : verification.markdown(context)); return 0;
|
||||
}
|
||||
@Command(name = "status", mixinStandardHelpOptions = true, description = "Set lifecycle status; transitions remain reversible.")
|
||||
int status(@Parameters(index = "0") String id, @Parameters(index = "1") Work.Status status) { return emit(works.status(root(), id, status), Format.markdown); }
|
||||
}
|
||||
@Command(name = "discussion", mixinStandardHelpOptions = true, description = "Append human or agent refinement entries.")
|
||||
public class DiscussionCommands {
|
||||
@Command(name = "add", mixinStandardHelpOptions = true)
|
||||
int add(@Parameters(index = "0") String id, @Option(names = "--text", required = true) String text,
|
||||
@Option(names = "--kind", defaultValue = "NOTE") DiscussionEntry.Kind kind,
|
||||
@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);
|
||||
}
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@Command(name = "decision", mixinStandardHelpOptions = true, description = "Persist draft formal decisions.")
|
||||
public class DecisionCommands {
|
||||
@Command(name = "draft", mixinStandardHelpOptions = true)
|
||||
int draft(@Parameters(index = "0") String id, @Option(names = "--title", required = true) String title,
|
||||
@Option(names = "--context", defaultValue = "") String context,
|
||||
@Option(names = "--approach", defaultValue = "") String approach,
|
||||
@Option(names = "--rationale", defaultValue = "") String rationale,
|
||||
@Option(names = "--evidence") List<String> evidence,
|
||||
@Option(names = "--author", defaultValue = "human") String author) {
|
||||
return emit(new DecisionService().draft(root(), id, title, context, approach, rationale, safe(evidence), author), Format.markdown);
|
||||
}
|
||||
@Command(name = "list", mixinStandardHelpOptions = true)
|
||||
int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
return emit(new DecisionService().list(root(), id), format);
|
||||
}
|
||||
}
|
||||
@Command(name = "artifact", mixinStandardHelpOptions = true, description = "Attach small evidence files with integrity metadata.")
|
||||
public class ArtifactCommands {
|
||||
@Command(name = "add", mixinStandardHelpOptions = true)
|
||||
int add(@Parameters(index = "0") String id, @Option(names = "--file", required = true) Path file,
|
||||
@Option(names = "--purpose", required = true) String purpose, @Option(names = "--origin") String origin,
|
||||
@Option(names = "--author", defaultValue = "human") String author) {
|
||||
return emit(new ArtifactService().attach(root(), id, resolve(file), purpose, origin, author), Format.markdown);
|
||||
}
|
||||
}
|
||||
private static <T> List<T> safe(List<T> list) { return list == null ? List.of() : list; }
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact", "verification"})
|
||||
package net.intrepid.aiengineering.cli;
|
||||
@@ -0,0 +1,30 @@
|
||||
package net.intrepid.aiengineering.decision;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public final class DecisionService {
|
||||
private final WorkService works = new WorkService();
|
||||
public List<DraftDecision> list(Path root, String id) {
|
||||
var work = works.load(root, id); Path folder = works.folder(root, id);
|
||||
return work.decisions().stream().map(ref -> {
|
||||
var decision = Documents.readDocument(Filespace.resolve(folder, "decisions/" + ref + ".md"), DraftDecision.class);
|
||||
if (!decision.id().equals(ref) || !decision.workId().equals(id)) throw ProtocolException.validation("Decision identity mismatch: " + ref);
|
||||
return decision;
|
||||
}).toList();
|
||||
}
|
||||
public DraftDecision draft(Path root, String workId, String title, String context, String approach, String rationale, List<String> evidence, String author) {
|
||||
return Filespace.locked(root, () -> {
|
||||
var work = works.load(root, workId);
|
||||
if (!work.artifacts().containsAll(evidence)) throw ProtocolException.invalid("Decision references an unknown artifact");
|
||||
String id = works.nextReference(work.decisions(), "DEC");
|
||||
var decision = new DraftDecision(1, id, workId, title, context, approach, List.of(), rationale, List.of(), List.of(),
|
||||
"DRAFT", author, Instant.now().toString(), evidence);
|
||||
Documents.writeDocument(Filespace.resolve(works.folder(root, workId), "decisions/" + id + ".md"), decision, false);
|
||||
works.addReference(root, workId, "decisions", id); return decision;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.intrepid.aiengineering.decision;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import net.intrepid.aiengineering.work.Work;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record DraftDecision(int schemaVersion, String id, String workId, String title, String context,
|
||||
String approach, List<String> alternatives, String rationale, List<String> risks, List<String> acceptanceCriteria,
|
||||
String approvalStatus, String author, String createdAt, List<String> evidence) {
|
||||
public DraftDecision {
|
||||
ProtocolException.schema(schemaVersion); Work.identifier(id, "DEC"); Work.identifier(workId, "WRK");
|
||||
ProtocolException.text(title, "decision title"); ProtocolException.text(author, "author"); Instant.parse(createdAt);
|
||||
if (!"DRAFT".equals(approvalStatus)) throw ProtocolException.validation("Milestone 1 only supports DRAFT decisions");
|
||||
if (context == null || approach == null || rationale == null) throw ProtocolException.validation("Missing decision fields");
|
||||
alternatives = List.copyOf(alternatives); risks = List.copyOf(risks);
|
||||
acceptanceCriteria = List.copyOf(acceptanceCriteria); evidence = List.copyOf(evidence);
|
||||
evidence.forEach(idValue -> Work.identifier(idValue, "ART"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
|
||||
package net.intrepid.aiengineering.decision;
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.intrepid.aiengineering.discussion;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import net.intrepid.aiengineering.work.Work;
|
||||
import java.time.Instant;
|
||||
|
||||
public record DiscussionEntry(int schemaVersion, String id, String workId, String discussionId, Kind kind,
|
||||
String author, String createdAt, String respondsTo, String text) {
|
||||
public enum Kind { NOTE, QUESTION, RESPONSE, SUGGESTION, ASSUMPTION, HYPOTHESIS, INVESTIGATION, ALTERNATIVE, ISSUE, CONCLUSION }
|
||||
public DiscussionEntry {
|
||||
ProtocolException.schema(schemaVersion); Work.identifier(id, "DSC"); Work.identifier(workId, "WRK");
|
||||
ProtocolException.text(discussionId, "discussionId"); ProtocolException.text(author, "author");
|
||||
ProtocolException.text(text, "discussion text"); Instant.parse(createdAt);
|
||||
if (kind == null) throw ProtocolException.validation("Missing discussion kind");
|
||||
if (respondsTo != null) Work.identifier(respondsTo, "DSC");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package net.intrepid.aiengineering.discussion;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public final class DiscussionService {
|
||||
private final WorkService works = new WorkService();
|
||||
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);
|
||||
if (!entry.id().equals(ref) || !entry.workId().equals(id)) throw ProtocolException.validation("Discussion identity mismatch: " + ref);
|
||||
return entry;
|
||||
}).toList();
|
||||
}
|
||||
public DiscussionEntry add(Path root, String workId, String text, DiscussionEntry.Kind kind, String author, String discussionId, String respondsTo) {
|
||||
return Filespace.locked(root, () -> {
|
||||
var work = works.load(root, workId);
|
||||
if (respondsTo != null && list(root, workId).stream().noneMatch(e -> e.id().equals(respondsTo)))
|
||||
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);
|
||||
works.addReference(root, workId, "discussions", id); return entry;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
|
||||
package net.intrepid.aiengineering.discussion;
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
import tools.jackson.core.StreamReadFeature;
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.cfg.EnumFeature;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Explicit protocol records, never Spring internal objects, are canonical. */
|
||||
public final class Documents {
|
||||
private static final YAMLMapper YAML = YAMLMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
|
||||
.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 Documents() {}
|
||||
public static String yaml(Object value) { return YAML.writeValueAsString(value); }
|
||||
public static String json(Object value) { return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value) + "\n"; }
|
||||
public static <T> T parse(String yaml, Class<T> type) {
|
||||
try { return YAML.readValue(yaml, type); }
|
||||
catch (RuntimeException e) { throw ProtocolException.validation("Invalid " + type.getSimpleName() + ": " + e.getMessage()); }
|
||||
}
|
||||
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);
|
||||
}
|
||||
public static void writeDocument(Path path, Object value, boolean replace) {
|
||||
String yaml = yaml(value).replaceFirst("^---\\n", "");
|
||||
Filespace.write(path, "---\n" + yaml + "---\n", replace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
|
||||
import static java.nio.file.StandardOpenOption.*;
|
||||
|
||||
/** Filesystem operations shared by the protocol adapters. Never executes project commands. */
|
||||
public final class Filespace {
|
||||
private Filespace() {}
|
||||
@FunctionalInterface public interface IoSupplier<T> { T get() throws IOException; }
|
||||
public static <T> T io(IoSupplier<T> action) {
|
||||
try { return action.get(); }
|
||||
catch (NoSuchFileException e) { throw ProtocolException.missing("Missing file: " + e.getFile()); }
|
||||
catch (IOException e) { throw new ProtocolException(1, "Filesystem operation failed: " + e.getMessage()); }
|
||||
}
|
||||
/** Rejects traversal and symlinks at every component, including paths that do not yet exist. */
|
||||
public static Path resolve(Path root, String relative) {
|
||||
Path value = Path.of(ProtocolException.text(relative, "path"));
|
||||
if (value.isAbsolute() || relative.contains("\\")) throw ProtocolException.invalid("Expected a relative path: " + relative);
|
||||
for (Path part : value) if (part.toString().equals("..")) throw ProtocolException.invalid("Path traversal rejected: " + relative);
|
||||
Path base = root.toAbsolutePath().normalize();
|
||||
Path result = base.resolve(value).normalize();
|
||||
if (!result.startsWith(base)) throw ProtocolException.invalid("Path escapes project: " + relative);
|
||||
Path current = base;
|
||||
if (Files.isSymbolicLink(base)) throw ProtocolException.invalid("Symlink rejected: " + base);
|
||||
for (Path part : base.relativize(result)) {
|
||||
current = current.resolve(part);
|
||||
if (Files.isSymbolicLink(current)) throw ProtocolException.invalid("Symlink rejected: " + current);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static void directory(Path path) { io(() -> { Files.createDirectories(path); return null; }); }
|
||||
public static List<Path> children(Path directory) {
|
||||
return io(() -> { try (var stream = Files.list(directory)) {
|
||||
return stream.filter(p -> !p.getFileName().toString().startsWith(".")).sorted().toList();
|
||||
}});
|
||||
}
|
||||
public static String read(Path path) { return io(() -> Files.readString(path)); }
|
||||
public static void write(Path path, String content, boolean replace) {
|
||||
writeBytes(path, content.getBytes(java.nio.charset.StandardCharsets.UTF_8), replace);
|
||||
}
|
||||
public static void writeBytes(Path path, byte[] bytes, boolean replace) {
|
||||
io(() -> {
|
||||
if (Files.exists(path, NOFOLLOW_LINKS) && !replace) throw ProtocolException.invalid("Already exists: " + path);
|
||||
if (Files.isSymbolicLink(path)) throw ProtocolException.invalid("Symlink rejected: " + path);
|
||||
Path temp = path.resolveSibling("." + path.getFileName() + "." + UUID.randomUUID() + ".tmp");
|
||||
try {
|
||||
try (var channel = FileChannel.open(temp, CREATE_NEW, WRITE)) {
|
||||
var buffer = java.nio.ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
if (replace) Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
else {
|
||||
// A hard link publishes the complete file atomically and cannot overwrite a competing writer.
|
||||
Files.createLink(path, temp);
|
||||
}
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
return null;
|
||||
});
|
||||
}
|
||||
public static <T> T locked(Path projectRoot, Supplier<T> operation) {
|
||||
Path lock = resolve(projectRoot, ".ai-engineering/.local/write.lock");
|
||||
directory(lock.getParent());
|
||||
return io(() -> {
|
||||
try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = channel.lock()) {
|
||||
return operation.get();
|
||||
} catch (java.nio.channels.OverlappingFileLockException e) {
|
||||
throw ProtocolException.invalid("Project is being modified by this process; retry after it completes");
|
||||
}
|
||||
});
|
||||
}
|
||||
public static void moveDirectory(Path from, Path to) {
|
||||
io(() -> {
|
||||
if (Files.exists(to, NOFOLLOW_LINKS)) throw ProtocolException.invalid("Already exists: " + to);
|
||||
Files.move(from, to, StandardCopyOption.ATOMIC_MOVE); return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
public final class ProtocolException extends RuntimeException {
|
||||
private final int exitCode;
|
||||
public ProtocolException(int exitCode, String message) { super(message); this.exitCode = exitCode; }
|
||||
public int exitCode() { return exitCode; }
|
||||
public static ProtocolException invalid(String message) { return new ProtocolException(2, message); }
|
||||
public static ProtocolException missing(String message) { return new ProtocolException(3, message); }
|
||||
public static ProtocolException validation(String message) { return new ProtocolException(4, message); }
|
||||
public static String text(String value, String field) {
|
||||
if (value == null || value.isBlank()) throw invalid(field + " must not be blank");
|
||||
return value;
|
||||
}
|
||||
public static void schema(int version) {
|
||||
if (version != 1) throw validation("Unsupported or missing schemaVersion: " + version);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {})
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
@@ -0,0 +1,32 @@
|
||||
package net.intrepid.aiengineering.project;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import java.util.List;
|
||||
|
||||
public record ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories) {
|
||||
public ProjectConfig {
|
||||
ProtocolException.schema(schemaVersion);
|
||||
if (project == null || repositories == null) throw ProtocolException.validation("project and repositories are required");
|
||||
repositories = List.copyOf(repositories);
|
||||
if (repositories.stream().map(Repository::id).distinct().count() != repositories.size())
|
||||
throw ProtocolException.validation("Duplicate repository IDs");
|
||||
}
|
||||
public record Identity(String id, String name) {
|
||||
public Identity { identifier(id); ProtocolException.text(name, "project name"); }
|
||||
}
|
||||
public record Access(boolean read, boolean edit) {
|
||||
public Access { if (edit && !read) throw ProtocolException.invalid("edit access requires read access"); }
|
||||
}
|
||||
public record Repository(String id, String path, String type, String language, Access access, List<String> validationCommands) {
|
||||
public Repository {
|
||||
identifier(id); ProtocolException.text(path, "repository path");
|
||||
if (!List.of("linked-git", "git-submodule").contains(type == null ? "" : type))
|
||||
throw ProtocolException.invalid("Repository type must be linked-git or git-submodule");
|
||||
access = access == null ? new Access(true, false) : access;
|
||||
validationCommands = validationCommands == null ? List.of() : List.copyOf(validationCommands);
|
||||
}
|
||||
}
|
||||
public static void identifier(String id) {
|
||||
if (id == null || !id.matches("[a-z][a-z0-9-]{0,63}")) throw ProtocolException.invalid("Invalid identifier: " + id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package net.intrepid.aiengineering.project;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.project.internal.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
public final class ProjectService {
|
||||
private final GitAdapter git = new ProcessGitAdapter();
|
||||
public Path discover(Path start, Path explicit) {
|
||||
if (explicit != null) {
|
||||
Path root = canonical(explicit);
|
||||
if (root.getFileName().toString().equals(".ai-engineering")) root = root.getParent();
|
||||
requireConfig(root); return root;
|
||||
}
|
||||
for (Path current = canonical(start); current != null; current = current.getParent()) {
|
||||
if (Files.exists(current.resolve(".ai-engineering"), LinkOption.NOFOLLOW_LINKS)) {
|
||||
requireConfig(current); return current;
|
||||
}
|
||||
}
|
||||
throw ProtocolException.missing("Engineering project not found; run ai-engineering init or use --project");
|
||||
}
|
||||
private static Path canonical(Path path) { return Filespace.io(() -> path.toAbsolutePath().normalize().toRealPath()); }
|
||||
private void requireConfig(Path root) {
|
||||
Path file = Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml");
|
||||
if (!Files.isRegularFile(file)) throw ProtocolException.missing("Missing project configuration: " + file);
|
||||
}
|
||||
public ProjectConfig initialize(Path root, String name) {
|
||||
root = canonical(root);
|
||||
var identity = new ProjectConfig.Identity(slug(name), name);
|
||||
var config = new ProjectConfig(1, identity, List.of());
|
||||
Path target = Filespace.resolve(root, ".ai-engineering");
|
||||
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.invalid("Project already exists: " + target);
|
||||
Path staging = Filespace.resolve(root, ".ai-engineering-init-" + UUID.randomUUID());
|
||||
Filespace.directory(staging);
|
||||
for (String dir : List.of("works", "contracts", ".local")) Filespace.directory(staging.resolve(dir));
|
||||
Filespace.write(staging.resolve("ai-engineering.yaml"), Documents.yaml(config), false);
|
||||
Filespace.write(staging.resolve(".gitignore"), ".local/\nworks/.*.tmp\nworks/*/runs/\n", false);
|
||||
Filespace.moveDirectory(staging, target);
|
||||
return config;
|
||||
}
|
||||
public static String slug(String text) {
|
||||
ProtocolException.text(text, "name");
|
||||
String result = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFD)
|
||||
.replaceAll("\\p{M}", "").toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-|-$", "");
|
||||
if (result.isBlank()) result = "project";
|
||||
if (!Character.isLetter(result.charAt(0))) result = "p-" + result;
|
||||
return result.substring(0, Math.min(result.length(), 60)).replaceAll("-$", "");
|
||||
}
|
||||
public ProjectConfig load(Path root) { return Documents.read(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), ProjectConfig.class); }
|
||||
public ProjectConfig addRepository(Path root, ProjectConfig.Repository repository) {
|
||||
return Filespace.locked(root, () -> {
|
||||
var config = load(root);
|
||||
if (config.repositories().stream().anyMatch(r -> r.id().equals(repository.id()))) throw ProtocolException.invalid("Repository already registered: " + repository.id());
|
||||
Path path = repositoryPath(root, repository);
|
||||
if (config.repositories().stream().anyMatch(r -> repositoryPath(root, r).equals(path))) throw ProtocolException.invalid("Repository path already registered: " + path);
|
||||
git.inspect(root, path, repository.type());
|
||||
var repositories = new ArrayList<>(config.repositories()); repositories.add(repository);
|
||||
var updated = new ProjectConfig(1, config.project(), repositories);
|
||||
Filespace.write(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), Documents.yaml(updated), true);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
public Path repositoryPath(Path root, ProjectConfig.Repository repository) {
|
||||
Path path = Filespace.resolve(root, repository.path());
|
||||
if (path.equals(root) || path.startsWith(root.resolve(".ai-engineering"))) throw ProtocolException.invalid("Repository must be a source directory beneath project root");
|
||||
return path;
|
||||
}
|
||||
public void validate(Path root) {
|
||||
var config = load(root); var paths = new HashSet<Path>();
|
||||
for (var repo : config.repositories()) {
|
||||
Path path = repositoryPath(root, repo);
|
||||
if (!paths.add(path)) throw ProtocolException.validation("Duplicate repository path: " + repo.path());
|
||||
git.inspect(root, path, repo.type());
|
||||
}
|
||||
}
|
||||
public record Revision(String repositoryId, String path, String head, boolean dirty) {
|
||||
public Revision {
|
||||
ProjectConfig.identifier(repositoryId); ProtocolException.text(path, "repository snapshot path");
|
||||
if (head == null || !head.matches("UNBORN|[a-f0-9]{40}|[a-f0-9]{64}"))
|
||||
throw ProtocolException.validation("Invalid repository revision: " + head);
|
||||
}
|
||||
}
|
||||
public List<Revision> revisions(Path root, List<String> ids) {
|
||||
var config = load(root);
|
||||
return ids.stream().map(id -> {
|
||||
var repo = config.repositories().stream().filter(r -> r.id().equals(id)).findFirst()
|
||||
.orElseThrow(() -> ProtocolException.validation("Unknown repository: " + id));
|
||||
var snapshot = git.inspect(root, repositoryPath(root, repo), repo.type());
|
||||
return new Revision(id, repo.path(), snapshot.head(), snapshot.dirty());
|
||||
}).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package net.intrepid.aiengineering.project.internal;
|
||||
|
||||
import java.nio.file.Path;
|
||||
public interface GitAdapter {
|
||||
record Snapshot(String head, boolean dirty) {}
|
||||
Snapshot inspect(Path root, Path repository, String type);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package net.intrepid.aiengineering.project.internal;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Read-only Git adapter. No init, checkout, submodule update, commit or network operations. */
|
||||
public final class ProcessGitAdapter implements GitAdapter {
|
||||
private String git(Path path, String... args) {
|
||||
return Filespace.io(() -> {
|
||||
var command = new java.util.ArrayList<String>(java.util.List.of("git", "--no-optional-locks", "-C", path.toString()));
|
||||
command.addAll(java.util.List.of(args));
|
||||
var builder = new ProcessBuilder(command).redirectErrorStream(true);
|
||||
builder.environment().keySet().removeIf(k -> k.startsWith("GIT_"));
|
||||
var process = builder.start();
|
||||
String output;
|
||||
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
var reader = executor.submit(() -> {
|
||||
try (var input = process.getInputStream()) {
|
||||
byte[] prefix = input.readNBytes(65536);
|
||||
input.transferTo(java.io.OutputStream.nullOutputStream());
|
||||
return new String(prefix, java.nio.charset.StandardCharsets.UTF_8).strip();
|
||||
}
|
||||
});
|
||||
try {
|
||||
if (!process.waitFor(10, TimeUnit.SECONDS)) { process.destroyForcibly(); throw ProtocolException.validation("Git inspection timed out: " + path); }
|
||||
output = reader.get(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
process.destroyForcibly(); Thread.currentThread().interrupt(); throw new java.io.IOException("Git inspection interrupted", e);
|
||||
} catch (java.util.concurrent.ExecutionException | java.util.concurrent.TimeoutException e) {
|
||||
process.destroyForcibly(); throw new java.io.IOException("Cannot read Git inspection output", e);
|
||||
}
|
||||
}
|
||||
if (process.exitValue() != 0) throw ProtocolException.validation("Git inspection failed: " + output);
|
||||
return output;
|
||||
});
|
||||
}
|
||||
@Override public Snapshot inspect(Path root, Path repository, String type) {
|
||||
if (!Files.isDirectory(repository)) throw ProtocolException.missing("Missing repository: " + repository);
|
||||
Path actual = Path.of(git(repository, "rev-parse", "--show-toplevel"));
|
||||
if (!Filespace.io(actual::toRealPath).equals(Filespace.io(repository::toRealPath)))
|
||||
throw ProtocolException.validation("Not an independent Git repository: " + repository);
|
||||
if (type.equals("git-submodule")) {
|
||||
String superproject = git(repository, "rev-parse", "--show-superproject-working-tree");
|
||||
if (superproject.isBlank() || !Filespace.io(() -> Path.of(superproject).toRealPath()).equals(Filespace.io(root::toRealPath)))
|
||||
throw ProtocolException.validation("Repository is not a submodule of this project: " + repository);
|
||||
}
|
||||
String head;
|
||||
try { head = git(repository, "rev-parse", "--verify", "HEAD"); }
|
||||
catch (ProtocolException e) { head = "UNBORN"; }
|
||||
return new Snapshot(head, !git(repository, "status", "--porcelain", "--untracked-files=normal").isBlank());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = "filesystem")
|
||||
package net.intrepid.aiengineering.project;
|
||||
@@ -0,0 +1,5 @@
|
||||
package net.intrepid.aiengineering.verification;
|
||||
import java.util.List;
|
||||
public record ValidationReport(boolean valid, List<String> issues) {
|
||||
public ValidationReport { issues = List.copyOf(issues); }
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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.*;
|
||||
import net.intrepid.aiengineering.artifact.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
public final class VerificationService {
|
||||
private final ProjectService projects = new ProjectService();
|
||||
private final WorkService works = new WorkService();
|
||||
private final DiscussionService discussions = new DiscussionService();
|
||||
private final DecisionService decisions = new DecisionService();
|
||||
private final ArtifactService artifacts = new ArtifactService();
|
||||
private void check(List<String> issues, Runnable operation) {
|
||||
try { operation.run(); } catch (RuntimeException e) { issues.add(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); }
|
||||
}
|
||||
public ValidationReport project(Path root) {
|
||||
var issues = new ArrayList<String>();
|
||||
check(issues, () -> projects.validate(root));
|
||||
check(issues, () -> {
|
||||
var all = works.list(root);
|
||||
Path counter = Filespace.resolve(works.workspace(root), ".sequence.yaml");
|
||||
if (!all.isEmpty()) {
|
||||
var sequence = Documents.read(counter, WorkService.Sequence.class);
|
||||
long max = all.stream().mapToLong(w -> Long.parseLong(w.id().substring(4))).max().orElse(0);
|
||||
if (sequence.lastWork() < max) issues.add("Work sequence is below the highest reserved ID");
|
||||
}
|
||||
all.forEach(w -> issues.addAll(work(root, w.id()).issues()));
|
||||
});
|
||||
for (String directory : List.of("works", "contracts", ".local"))
|
||||
check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(root, ".ai-engineering/" + directory))) issues.add("Missing project directory: " + directory); });
|
||||
return new ValidationReport(issues.isEmpty(), issues);
|
||||
}
|
||||
public ValidationReport work(Path root, String id) {
|
||||
var issues = new ArrayList<String>();
|
||||
check(issues, () -> {
|
||||
Work work = works.load(root, id); Path folder = works.folder(root, id);
|
||||
var registered = projects.load(root).repositories().stream().map(ProjectConfig.Repository::id).toList();
|
||||
for (var revision : work.repositories()) {
|
||||
if (!registered.contains(revision.repositoryId())) issues.add("Unknown Work repository: " + revision.repositoryId());
|
||||
check(issues, () -> Filespace.resolve(root, revision.path()));
|
||||
}
|
||||
for (String directory : List.of("discussions", "decisions", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
|
||||
check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(folder, directory))) issues.add("Missing Work directory: " + directory); });
|
||||
check(issues, () -> {
|
||||
var entries = discussions.list(root, id);
|
||||
var seen = new HashSet<String>();
|
||||
for (var entry : entries) {
|
||||
if (entry.respondsTo() != null && !seen.contains(entry.respondsTo())) issues.add("Discussion response must reference an earlier entry: " + entry.id());
|
||||
seen.add(entry.id());
|
||||
}
|
||||
});
|
||||
check(issues, () -> decisions.list(root, id).forEach(d -> {
|
||||
if (!work.artifacts().containsAll(d.evidence())) issues.add("Missing decision evidence: " + d.id());
|
||||
}));
|
||||
check(issues, () -> artifacts.validate(root, id));
|
||||
check(issues, () -> orphans(issues, folder, "discussions", work.discussions().stream().map(s -> s + ".md").toList()));
|
||||
check(issues, () -> orphans(issues, folder, "decisions", work.decisions().stream().map(s -> s + ".md").toList()));
|
||||
check(issues, () -> orphans(issues, folder, "artifacts/evidence", work.artifacts()));
|
||||
});
|
||||
return new ValidationReport(issues.isEmpty(), issues);
|
||||
}
|
||||
private void orphans(List<String> issues, Path folder, String directory, List<String> expected) {
|
||||
for (Path entry : Filespace.children(Filespace.resolve(folder, directory))) {
|
||||
Filespace.resolve(folder, folder.relativize(entry).toString());
|
||||
if (!expected.contains(entry.getFileName().toString())) issues.add("Unreferenced protocol file: " + directory + "/" + entry.getFileName());
|
||||
}
|
||||
}
|
||||
public record Context(int schemaVersion, Work work, List<DiscussionEntry> discussionHistory, List<DraftDecision> decisions,
|
||||
List<String> outstandingQuestions, List<Artifact> artifacts) {}
|
||||
public Context context(Path root, String id) {
|
||||
var report = work(root, id);
|
||||
if (!report.valid()) throw ProtocolException.validation(String.join("; ", report.issues()));
|
||||
var history = discussions.list(root, id);
|
||||
var answered = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.RESPONSE || e.kind() == DiscussionEntry.Kind.CONCLUSION)
|
||||
.map(DiscussionEntry::respondsTo).filter(Objects::nonNull).toList();
|
||||
var outstanding = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.QUESTION || e.kind() == DiscussionEntry.Kind.ISSUE)
|
||||
.filter(e -> !answered.contains(e.id())).map(e -> e.id() + ": " + e.text()).toList();
|
||||
return new Context(1, works.load(root, id), history, decisions.list(root, id), outstanding, artifacts.list(root, id));
|
||||
}
|
||||
public String markdown(Context context) {
|
||||
var w = context.work();
|
||||
var result = new StringBuilder("# " + w.id() + " — " + w.title() + "\n\nProtocol schema: 1\n\nStatus: " + w.status() + "\n");
|
||||
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, "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();
|
||||
}
|
||||
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 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,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact"})
|
||||
package net.intrepid.aiengineering.verification;
|
||||
@@ -0,0 +1,47 @@
|
||||
package net.intrepid.aiengineering.work;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import net.intrepid.aiengineering.project.ProjectService.Revision;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
public record Work(int schemaVersion, String id, String title, String description, String goal, String motivation,
|
||||
List<String> constraints, List<String> acceptanceCriteria, Status status, String createdAt, String updatedAt,
|
||||
String author, List<Revision> repositories, List<String> discussions, List<String> decisions, List<String> artifacts) {
|
||||
public enum Status { OPEN, ACTIVE, BLOCKED, COMPLETED, CANCELLED }
|
||||
public Work {
|
||||
ProtocolException.schema(schemaVersion); identifier(id, "WRK");
|
||||
ProtocolException.text(title, "title"); ProtocolException.text(goal, "goal"); ProtocolException.text(author, "author");
|
||||
if (description == null || motivation == null || status == null) throw ProtocolException.validation("Missing Work fields");
|
||||
Instant.parse(createdAt); Instant.parse(updatedAt);
|
||||
constraints = List.copyOf(constraints); acceptanceCriteria = List.copyOf(acceptanceCriteria);
|
||||
repositories = List.copyOf(repositories); discussions = List.copyOf(discussions);
|
||||
decisions = List.copyOf(decisions); artifacts = List.copyOf(artifacts);
|
||||
checkRefs(discussions, "DSC"); checkRefs(decisions, "DEC"); checkRefs(artifacts, "ART");
|
||||
if (repositories.stream().map(Revision::repositoryId).distinct().count() != repositories.size())
|
||||
throw ProtocolException.validation("Duplicate Work repository references");
|
||||
}
|
||||
private static void checkRefs(List<String> refs, String prefix) {
|
||||
refs.forEach(id -> identifier(id, prefix));
|
||||
if (refs.stream().distinct().count() != refs.size()) throw ProtocolException.validation("Duplicate " + prefix + " references");
|
||||
}
|
||||
public static void identifier(String id, String prefix) {
|
||||
if (id == null || !id.matches(prefix + "-[0-9]{4,9}") || Long.parseLong(id.substring(4)) == 0)
|
||||
throw ProtocolException.invalid("Invalid " + prefix + " identifier: " + id);
|
||||
}
|
||||
public Work reference(String kind, String reference) {
|
||||
var refs = new java.util.ArrayList<>(switch (kind) {
|
||||
case "discussions" -> discussions; case "decisions" -> decisions; case "artifacts" -> artifacts;
|
||||
default -> throw ProtocolException.invalid("Invalid reference kind: " + kind);
|
||||
});
|
||||
refs.add(reference);
|
||||
return new Work(1, id, title, description, goal, motivation, constraints, acceptanceCriteria, status,
|
||||
createdAt, Instant.now().toString(), author, repositories,
|
||||
kind.equals("discussions") ? refs : discussions, kind.equals("decisions") ? refs : decisions,
|
||||
kind.equals("artifacts") ? refs : artifacts);
|
||||
}
|
||||
public Work withStatus(Status value) {
|
||||
return new Work(1, id, title, description, goal, motivation, constraints, acceptanceCriteria, value,
|
||||
createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package net.intrepid.aiengineering.work;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.project.ProjectService;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
public final class WorkService {
|
||||
private final ProjectService projects = new ProjectService();
|
||||
public Path workspace(Path root) { return Filespace.resolve(root, ".ai-engineering/works"); }
|
||||
public List<Work> list(Path root) {
|
||||
var seen = new HashSet<String>(); var result = new ArrayList<Work>();
|
||||
for (Path folder : Filespace.children(workspace(root))) {
|
||||
Path safe = Filespace.resolve(root, root.relativize(folder).toString());
|
||||
if (!Files.isDirectory(safe)) throw ProtocolException.validation("Unexpected file in works: " + folder);
|
||||
var work = Documents.readDocument(Filespace.resolve(safe, "work.md"), Work.class);
|
||||
if (!seen.add(work.id())) throw ProtocolException.validation("Duplicate Work ID: " + work.id());
|
||||
if (!folder.getFileName().toString().startsWith(work.id() + "-")) throw ProtocolException.validation("Work directory/ID mismatch: " + folder);
|
||||
result.add(work);
|
||||
}
|
||||
return result.stream().sorted(Comparator.comparing(Work::id)).toList();
|
||||
}
|
||||
public Work load(Path root, String id) {
|
||||
Work.identifier(id, "WRK");
|
||||
return list(root).stream().filter(w -> w.id().equals(id)).findFirst()
|
||||
.orElseThrow(() -> ProtocolException.missing("Work not found: " + id));
|
||||
}
|
||||
public Path folder(Path root, String id) {
|
||||
load(root, id);
|
||||
return Filespace.children(workspace(root)).stream().filter(p -> p.getFileName().toString().startsWith(id + "-"))
|
||||
.map(p -> Filespace.resolve(root, root.relativize(p).toString())).findFirst().orElseThrow();
|
||||
}
|
||||
public Work create(Path root, String title, String description, String goal, String motivation,
|
||||
List<String> constraints, List<String> criteria, List<String> repositories, String author) {
|
||||
return Filespace.locked(root, () -> {
|
||||
list(root); // Refuse to allocate an ID in a corrupt project.
|
||||
// The sequence is canonical; a crash may leave gaps, but identities are never reused.
|
||||
Path counter = Filespace.resolve(workspace(root), ".sequence.yaml");
|
||||
long last = Files.exists(counter) ? Documents.read(counter, Sequence.class).lastWork() : 0;
|
||||
long max = list(root).stream().mapToLong(w -> Long.parseLong(w.id().substring(4))).max().orElse(0);
|
||||
long next = Math.max(last, max) + 1;
|
||||
if (next > 999999999) throw ProtocolException.validation("Work ID space exhausted");
|
||||
String id = "WRK-%04d".formatted(next);
|
||||
String now = Instant.now().toString();
|
||||
var work = new Work(1, id, title, description, goal.isBlank() ? title : goal, motivation, constraints, criteria,
|
||||
Work.Status.OPEN, now, now, author, projects.revisions(root, repositories), List.of(), List.of(), List.of());
|
||||
Path target = Filespace.resolve(workspace(root), id + "-" + ProjectService.slug(title));
|
||||
Path staging = Filespace.resolve(workspace(root), "." + id + "-" + UUID.randomUUID() + ".tmp");
|
||||
Filespace.directory(staging);
|
||||
for (String dir : List.of("discussions", "decisions", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
|
||||
Filespace.directory(Filespace.resolve(staging, dir));
|
||||
Documents.writeDocument(staging.resolve("work.md"), work, false);
|
||||
// Reserve before publishing. A crash can leave a gap, never reuse a reserved identity.
|
||||
Filespace.write(counter, Documents.yaml(new Sequence(1, next)), Files.exists(counter));
|
||||
Filespace.moveDirectory(staging, target); return work;
|
||||
});
|
||||
}
|
||||
public record Sequence(int schemaVersion, long lastWork) {
|
||||
public Sequence { ProtocolException.schema(schemaVersion); if (lastWork < 0) throw ProtocolException.validation("Invalid Work sequence"); }
|
||||
}
|
||||
/** Called inside the caller's project lock after publishing the referenced file. */
|
||||
public void addReference(Path root, String id, String kind, String reference) {
|
||||
Documents.writeDocument(Filespace.resolve(folder(root, id), "work.md"), load(root, id).reference(kind, reference), true);
|
||||
}
|
||||
public Work status(Path root, String id, Work.Status value) {
|
||||
return Filespace.locked(root, () -> {
|
||||
Work updated = load(root, id).withStatus(value);
|
||||
Documents.writeDocument(Filespace.resolve(folder(root, id), "work.md"), updated, true); return updated;
|
||||
});
|
||||
}
|
||||
public String nextReference(List<String> ids, String prefix) {
|
||||
long max = ids.stream().mapToLong(id -> Long.parseLong(id.substring(4))).max().orElse(0);
|
||||
if (max >= 999999999) throw ProtocolException.validation("ID space exhausted: " + prefix);
|
||||
return prefix + "-%04d".formatted(max + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project"})
|
||||
package net.intrepid.aiengineering.work;
|
||||
Reference in New Issue
Block a user