feat: adopt local SQLite engineering memory and quality gates
This commit is contained in:
@@ -23,6 +23,8 @@ public final class NativeHints implements RuntimeHintsRegistrar {
|
||||
net.intrepid.aiengineering.planning.Experiment.Outcome.class,
|
||||
PlanCoordinator.PlanSource.class, PlanCoordinator.Receipt.class, PlanCoordinator.Evaluation.class,
|
||||
PlanCoordinator.Result.class, PlanCoordinator.Mutation.class, Work.Aggregation.class,
|
||||
QualityGates.Definition.class, QualityGates.Result.class, QualityGates.View.class, QualityGates.Outcome.class,
|
||||
StorageMigration.State.class, StorageMigration.Report.class,
|
||||
Work.Event.class, Work.Completion.class, Work.CriterionResult.class, Work.Integration.class,
|
||||
Work.Delegation.class, Epic.class, Epic.Link.class, Epic.Authorization.class,
|
||||
EpicCoordinator.Child.class, EpicCoordinator.Evaluation.class, EpicCoordinator.ChildReceipt.class, EpicCoordinator.Receipt.class,
|
||||
@@ -40,9 +42,11 @@ public final class NativeHints implements RuntimeHintsRegistrar {
|
||||
DiscussionImport.Source.class, DiscussionImport.SourceView.class, DiscussionImport.AgendaView.class,
|
||||
DiscussionImport.Entry.class, DiscussionImport.Report.class, DiscussionImport.ImportedAgenda.class,
|
||||
DiscussionImport.Receipt.class, DiscussionImport.Action.class,
|
||||
Artifact.class, ValidationReport.class, VerificationService.Context.class, DiscussionService.MigrationReport.class}) {
|
||||
Artifact.class, ProtocolReceipt.class, ProtocolReceipt.Source.class, ArtifactPublication.Intent.class,
|
||||
ValidationReport.class, VerificationService.Context.class, DiscussionService.MigrationReport.class}) {
|
||||
hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
|
||||
}
|
||||
hints.resources().registerPattern("protocol/*");
|
||||
hints.resources().registerPattern("sqlite/*");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,8 @@ public final class AgentService {
|
||||
/** Source fingerprint excludes run bookkeeping and Work modification time. */
|
||||
public String fingerprint(AgentContext context) {
|
||||
var w=context.work(); var data=new LinkedHashMap<String,Object>();
|
||||
data.put("project",context.project()); data.put("workId",w.id()); data.put("title",w.title()); data.put("description",w.description());
|
||||
var project = Documents.jsonTree(context.project()); project.remove("storage");
|
||||
data.put("project",project); data.put("workId",w.id()); data.put("title",w.title()); data.put("description",w.description());
|
||||
if (w.guidance() != null) data.put("guidance", w.guidance());
|
||||
data.put("goal",w.goal()); data.put("motivation",w.motivation()); data.put("constraints",w.constraints()); data.put("criteria",w.acceptanceCriteria());
|
||||
data.put("status",w.status()); data.put("archived",w.archived()); data.put("repositories",w.repositories());
|
||||
@@ -76,7 +77,7 @@ public final class AgentService {
|
||||
public List<AgentRun> history(Path root,String work) {
|
||||
var w=works.load(root,work); var all=new ArrayList<AgentRun>(); var requests=new HashSet<String>();
|
||||
for(String id:w.agentRuns()) {
|
||||
var run=Documents.readMarkdownDocument(path(root,work,id),AgentRun.class,"task");
|
||||
var run=RecordStorage.read(path(root,work,id),AgentRun.class,"task");
|
||||
if(!run.id().equals(id)||!run.workId().equals(work)||!requests.add(run.requestId())) throw ProtocolException.validation("Invalid run identity/request: "+id);
|
||||
for(var reference:run.applied()) {
|
||||
var ids=switch(reference.kind()) {case "topics"->w.topics(); case "surveys"->w.surveys(); case "dispositions"->w.dispositions(); case "decisions"->w.decisions(); default->w.discussions();};
|
||||
@@ -148,7 +149,7 @@ public final class AgentService {
|
||||
||output.surveys().stream().flatMap(s->s.questions().stream()).anyMatch(q->q.sources().contains("@request"));
|
||||
}
|
||||
private void write(Path root,AgentRun run,boolean replace) {
|
||||
var p=path(root,run.workId(),run.id()); Filespace.directory(p.getParent()); Documents.writeMarkdownDocument(p,run,"task",replace);
|
||||
var p=path(root,run.workId(),run.id()); Filespace.directory(p.getParent()); RecordStorage.write(p,run,AgentRun.class,"task",replace);
|
||||
}
|
||||
public AgentRun run(Path root,String work,String task,String activity,String requester,String requestId) {
|
||||
text(task,"task"); text(requester,"requester"); if(activity!=null) ProjectConfig.identifier(activity);
|
||||
@@ -173,7 +174,8 @@ public final class AgentService {
|
||||
var output=response.proposal();
|
||||
validate(root,context,output,selected);
|
||||
var provenance=selection.invocation()==null&&response.invocation()==null?null:new AgentRun.Provenance(selection.invocation(),response.invocation());
|
||||
return Filespace.locked(root,()->{
|
||||
var attempted = new AgentRun[1];
|
||||
try { return Filespace.locked(root,()->{
|
||||
works.editable(root,work);
|
||||
// Another process may have applied the same no-op/summary request without changing semantic sources.
|
||||
for(var old:history(root,work)) if(old.requestId().equals(key)) {
|
||||
@@ -184,6 +186,7 @@ public final class AgentService {
|
||||
new ArtifactService().validate(root,work); validate(root,context,output,selected);
|
||||
String id=works.nextReference(works.load(root,work).agentRuns(),"RUN"), now=Instant.now().toString();
|
||||
var run=new AgentRun(1,id,work,key,task,activity,selectedActivity,requester,executor,hash,AgentRun.Status.APPLYING,output,List.of(),"",now,now,provenance);
|
||||
attempted[0] = run;
|
||||
write(root,run,false); works.addReference(root,work,"agentRuns",id); var applied=new ArrayList<AgentRun.Applied>();
|
||||
try {
|
||||
String requestSource=null;
|
||||
@@ -215,10 +218,32 @@ public final class AgentService {
|
||||
}
|
||||
var completed=run.finish(AgentRun.Status.COMPLETED,applied,""); write(root,completed,true); works.touched(root,work,completed.updatedAt()); return completed;
|
||||
} catch(RuntimeException failure) {
|
||||
if (SqliteDatabase.active(root)) throw failure;
|
||||
try { write(root,run.finish(AgentRun.Status.FAILED,applied,failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage()),true); }
|
||||
catch(RuntimeException secondary) { failure.addSuppressed(secondary); }
|
||||
throw new ProtocolException(failure instanceof ProtocolException p?p.exitCode():1,"Run "+id+" failed; inspect agent show: "+failure.getMessage());
|
||||
}
|
||||
});
|
||||
}); } catch (RuntimeException failure) {
|
||||
if (!SqliteDatabase.active(root) || attempted[0] == null) throw failure;
|
||||
// The proposal transaction has rolled back. Publish only its diagnostic in a fresh transaction.
|
||||
AgentRun failed;
|
||||
try {
|
||||
failed = Filespace.locked(root, () -> {
|
||||
works.editable(root, work);
|
||||
if (history(root, work).stream().anyMatch(old -> old.requestId().equals(key)))
|
||||
throw ProtocolException.validation("Request already recorded during failure recovery: " + key);
|
||||
var original = attempted[0];
|
||||
String id = works.nextReference(works.load(root, work).agentRuns(), "RUN");
|
||||
String diagnostic = failure.getMessage() == null ? failure.getClass().getSimpleName() : failure.getMessage();
|
||||
var record = new AgentRun(1, id, work, key, task, activity, selectedActivity, requester, executor, hash,
|
||||
AgentRun.Status.FAILED, output, List.of(), diagnostic, original.createdAt(), Instant.now().toString(), provenance);
|
||||
write(root, record, false); works.addReference(root, work, "agentRuns", id); return record;
|
||||
});
|
||||
} catch (RuntimeException diagnosticFailure) {
|
||||
failure.addSuppressed(diagnosticFailure); throw failure;
|
||||
}
|
||||
throw new ProtocolException(failure instanceof ProtocolException p ? p.exitCode() : 1,
|
||||
"Run " + failed.id() + " rolled back; inspect agent show: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
|
||||
/** Two-phase retirement: checked facts commit before any external payload is removed. */
|
||||
public final class ArtifactLifecycle {
|
||||
private ArtifactLifecycle() {}
|
||||
public static String state(Path root, String work, String artifact) {
|
||||
if (!SqliteDatabase.active(root)) return "RETAINED_LEGACY";
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT state FROM artifact_lifecycle WHERE work_id=? AND artifact_id=?")) {
|
||||
statement.setString(1, work); statement.setString(2, artifact);
|
||||
try (var row = statement.executeQuery()) { return row.next() ? row.getString(1) : "RETAINED_LEGACY"; }
|
||||
}
|
||||
});
|
||||
}
|
||||
public static int pending(Path root, String work) {
|
||||
if (!SqliteDatabase.active(root)) return 0;
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT count(*) FROM artifact_lifecycle WHERE work_id=? AND state='DISCARD_PENDING'")) {
|
||||
statement.setString(1, work);
|
||||
try (var row = statement.executeQuery()) { return row.next() ? row.getInt(1) : 0; }
|
||||
}
|
||||
});
|
||||
}
|
||||
static void register(Path root, Artifact artifact, String state) {
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("INSERT INTO artifact_lifecycle(work_id,artifact_id,state,checked_sha256,checked_at) VALUES (?,?,?,?,?)")) {
|
||||
statement.setString(1, artifact.workId()); statement.setString(2, artifact.id()); statement.setString(3, state);
|
||||
statement.setString(4, state.equals("STRUCTURED") ? artifact.sha256() : null);
|
||||
statement.setString(5, state.equals("STRUCTURED") ? Instant.now().toString() : null); statement.executeUpdate();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
static void checked(Path root, Artifact artifact) {
|
||||
SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT checked_sha256,checked_at FROM artifact_lifecycle WHERE work_id=? AND artifact_id=?")) {
|
||||
statement.setString(1, artifact.workId()); statement.setString(2, artifact.id());
|
||||
try (var row = statement.executeQuery()) {
|
||||
if (!row.next() || !artifact.sha256().equals(row.getString(1)) || row.getString(2) == null)
|
||||
throw ProtocolException.validation("Missing validated artifact retirement: " + artifact.id());
|
||||
Instant.parse(row.getString(2));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
public static void prepareCompleted(Path root, String work) {
|
||||
if (!SqliteDatabase.active(root)) return;
|
||||
if (new WorkService().load(root, work).status() != Work.Status.COMPLETED) throw ProtocolException.validation("Pending Work still needs its evidence");
|
||||
var artifacts = new ArtifactService(); artifacts.validate(root, work);
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
for (var artifact : artifacts.list(root, work)) if (state(root, work, artifact.id()).equals("AVAILABLE")) {
|
||||
try (var statement = connection.prepareStatement("UPDATE artifact_lifecycle SET state='DISCARD_PENDING',checked_sha256=?,checked_at=? WHERE work_id=? AND artifact_id=? AND state='AVAILABLE'")) {
|
||||
statement.setString(1, artifact.sha256()); statement.setString(2, Instant.now().toString());
|
||||
statement.setString(3, work); statement.setString(4, artifact.id()); statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
SqliteDatabase.afterCommit(root, () -> recover(root, work)); return null;
|
||||
});
|
||||
}
|
||||
public static int recover(Path root, String work) {
|
||||
if (!SqliteDatabase.active(root)) return 0;
|
||||
return Filespace.locked(root, () -> {
|
||||
var artifacts = new ArtifactService(); int count = 0;
|
||||
for (var artifact : artifacts.list(root, work)) if (state(root, work, artifact.id()).equals("DISCARD_PENDING")) {
|
||||
checked(root, artifact);
|
||||
Path path = Filespace.resolve(new WorkService().folder(root, work), artifact.path());
|
||||
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
artifacts.validatePayload(path, artifact);
|
||||
Filespace.io(() -> { Files.delete(path); return null; });
|
||||
}
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("UPDATE artifact_lifecycle SET state='DISCARDED' WHERE work_id=? AND artifact_id=? AND state='DISCARD_PENDING'")) {
|
||||
statement.setString(1, work); statement.setString(2, artifact.id()); statement.executeUpdate();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** A tiny temporary intent identifies files owned by an interrupted publication. */
|
||||
public final class ArtifactPublication {
|
||||
private ArtifactPublication() {}
|
||||
public record Intent(Artifact artifact, String target, String staging) {}
|
||||
static Path begin(Path root, Artifact artifact, Path target, Path staging) {
|
||||
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.validation("Existing artifact publication requires recovery before retry: " + target);
|
||||
Path directory = Filespace.resolve(root, ".ai-engineering/.local/artifact-publications"); Filespace.directory(directory);
|
||||
Path journal = directory.resolve(UUID.randomUUID() + ".json");
|
||||
Filespace.write(journal, Documents.json(new Intent(artifact, root.relativize(target).toString(), root.relativize(staging).toString())), false);
|
||||
SqliteDatabase.afterRollback(root, () -> recoverOne(root, journal));
|
||||
SqliteDatabase.afterCommit(root, () -> recoverOne(root, journal));
|
||||
return journal;
|
||||
}
|
||||
private static void removeOwned(Path directory, Artifact artifact) {
|
||||
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) return;
|
||||
Path payload = Filespace.resolve(directory, "payload");
|
||||
try (var files = Filespace.io(() -> Files.list(directory))) {
|
||||
if (files.anyMatch(file -> !file.getFileName().toString().equals("payload")))
|
||||
throw ProtocolException.validation("Unexpected publication residue; inspect " + directory);
|
||||
}
|
||||
if (Files.exists(payload, LinkOption.NOFOLLOW_LINKS)) new ArtifactService().validatePayload(payload, artifact);
|
||||
Filespace.io(() -> { Files.deleteIfExists(payload); Files.delete(directory); return null; });
|
||||
}
|
||||
private static void recoverOne(Path root, Path journal) {
|
||||
var intent = Documents.readJson(journal, Intent.class); var artifact = intent.artifact();
|
||||
Path target = Filespace.resolve(root, intent.target()), staging = Filespace.resolve(root, intent.staging());
|
||||
Path parent = target.getParent();
|
||||
if (!target.getFileName().toString().equals(artifact.id()) || !parent.endsWith("artifacts/evidence")
|
||||
|| !target.startsWith(root.resolve(".ai-engineering/works"))
|
||||
|| !staging.getParent().equals(parent) || !staging.getFileName().toString().startsWith("." + artifact.id() + "-"))
|
||||
throw ProtocolException.validation("Invalid artifact publication intent: " + journal);
|
||||
int current = SqliteRecords.current(root, artifact.workId(), "artifact", artifact.id());
|
||||
if (current == 0) removeOwned(target, artifact);
|
||||
else if (!SqliteRecords.get(root, artifact.workId(), "artifact", artifact.id(), 0, Artifact.class).equals(artifact))
|
||||
throw ProtocolException.validation("Publication identity changed; inspect " + journal);
|
||||
removeOwned(staging, artifact);
|
||||
Filespace.io(() -> { Files.delete(journal); return null; });
|
||||
}
|
||||
public static int recover(Path root) {
|
||||
if (!SqliteDatabase.active(root)) return 0;
|
||||
return Filespace.locked(root, () -> {
|
||||
Path directory = Filespace.resolve(root, ".ai-engineering/.local/artifact-publications");
|
||||
if (!Files.exists(directory)) return 0;
|
||||
var journals = Filespace.children(directory);
|
||||
for (Path journal : journals) {
|
||||
Path safe = Filespace.resolve(directory, journal.getFileName().toString());
|
||||
if (!safe.getFileName().toString().matches("[0-9a-f-]{36}\\.json")) throw ProtocolException.validation("Unexpected publication journal: " + journal);
|
||||
recoverOne(root, safe);
|
||||
}
|
||||
return journals.size();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ public final class ArtifactService {
|
||||
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);
|
||||
var artifact = SqliteDatabase.active(root) ? SqliteRecords.get(root, id, "artifact", ref, 0, Artifact.class)
|
||||
: 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());
|
||||
@@ -39,26 +40,80 @@ public final class ArtifactService {
|
||||
works.addReference(root, workId, "artifacts", id); return artifact;
|
||||
});
|
||||
}
|
||||
/** Internal aggregation facts live in typed columns/rows, with legacy files readable unchanged. */
|
||||
public Artifact attachReceipt(Path root, String work, Object receipt, String purpose, String origin, String author) {
|
||||
if (!SqliteDatabase.active(root)) return attachBytes(root, work, Documents.json(receipt).getBytes(java.nio.charset.StandardCharsets.UTF_8), purpose, origin, author);
|
||||
return Filespace.locked(root, () -> {
|
||||
var w = works.editable(root, work); String id = works.nextReference(w.artifacts(), "ART");
|
||||
var data = ProtocolReceipt.from(id, work, receipt);
|
||||
String json = Documents.json(receipt);
|
||||
if (!Documents.json(data.content()).equals(json)) throw ProtocolException.validation("Unsupported protocol receipt fields");
|
||||
byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
var artifact = new Artifact(1, id, work, origin, purpose, "artifacts/evidence/" + id + "/payload", hash(bytes), bytes.length, author, Instant.now().toString());
|
||||
SqliteRecords.put(root, work, "receipt", id, data, ProtocolReceipt.class, false, 1);
|
||||
SqliteRecords.put(root, work, "artifact", id, artifact, Artifact.class, false, 1);
|
||||
ArtifactLifecycle.register(root, artifact, "STRUCTURED");
|
||||
works.addReference(root, work, "artifacts", id); return artifact;
|
||||
});
|
||||
}
|
||||
public <T> T readReceipt(Path root, String work, Artifact artifact, Class<T> type) {
|
||||
if (!ArtifactLifecycle.state(root, work, artifact.id()).equals("STRUCTURED"))
|
||||
return Documents.readJson(Filespace.resolve(works.folder(root, work), artifact.path()), type);
|
||||
String json = receiptJson(root, artifact);
|
||||
return Documents.parseJson(json, type);
|
||||
}
|
||||
private String receiptJson(Path root, Artifact artifact) {
|
||||
var receipt = SqliteRecords.get(root, artifact.workId(), "receipt", artifact.id(), 0, ProtocolReceipt.class);
|
||||
String json = Documents.json(receipt.content()); byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (!hash(bytes).equals(artifact.sha256()) || bytes.length != artifact.size()) throw ProtocolException.validation("Structured receipt integrity mismatch: " + artifact.id());
|
||||
ArtifactLifecycle.checked(root, artifact); return json;
|
||||
}
|
||||
/** Normal evidence format in an unpublished Work folder; caller publishes its Work references. */
|
||||
public Artifact writePrepared(Path folder, String workId, String id, byte[] content, String purpose, String origin, String author) {
|
||||
Work.identifier(workId, "WRK"); Work.identifier(id, "ART"); byte[] bytes = content.clone();
|
||||
if (bytes.length > MAX_BYTES) throw ProtocolException.invalid("Evidence exceeds 1 MiB");
|
||||
Path parent = Filespace.resolve(folder, "artifacts/evidence");
|
||||
Path stage = Filespace.resolve(parent, "." + id + "-" + UUID.randomUUID() + ".tmp"); Filespace.directory(stage);
|
||||
Path stage = Filespace.resolve(parent, "." + id + "-" + UUID.randomUUID() + ".tmp");
|
||||
var artifact = new Artifact(1, id, workId, origin, purpose,
|
||||
"artifacts/evidence/" + id + "/payload", hash(bytes), bytes.length, author, Instant.now().toString());
|
||||
Path sqliteRoot = RecordStorage.sqliteRoot(folder);
|
||||
if (sqliteRoot != null) ArtifactPublication.begin(sqliteRoot, artifact, Filespace.resolve(parent, id), stage);
|
||||
Filespace.directory(stage);
|
||||
Filespace.writeBytes(stage.resolve("payload"), bytes, false);
|
||||
Filespace.write(stage.resolve("artifact.yaml"), Documents.yaml(artifact), false);
|
||||
Filespace.moveDirectory(stage, Filespace.resolve(parent, id)); return artifact;
|
||||
if (sqliteRoot == null) Filespace.write(stage.resolve("artifact.yaml"), Documents.yaml(artifact), false);
|
||||
Filespace.moveDirectory(stage, Filespace.resolve(parent, id));
|
||||
if (sqliteRoot != null) {
|
||||
SqliteRecords.put(sqliteRoot, workId, "artifact", id, artifact, Artifact.class, false, 1);
|
||||
ArtifactLifecycle.register(sqliteRoot, artifact, origin.startsWith("discussion-framework:") || origin.startsWith("ai-engineering:discussion-import:") ? "RETAINED_LEGACY" : "AVAILABLE");
|
||||
}
|
||||
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());
|
||||
String state = ArtifactLifecycle.state(root, id, artifact.id());
|
||||
if (state.equals("STRUCTURED")) { receiptJson(root, artifact); continue; }
|
||||
if (state.equals("DISCARDED") || state.equals("DISCARD_PENDING")) {
|
||||
ArtifactLifecycle.checked(root, artifact);
|
||||
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) continue;
|
||||
}
|
||||
validatePayload(path, artifact);
|
||||
}
|
||||
}
|
||||
void validatePayload(Path path, Artifact artifact) {
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) 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());
|
||||
}
|
||||
public void requireAvailable(Path root, String work, List<String> evidence) {
|
||||
var all = list(root, work);
|
||||
for (String id : evidence) {
|
||||
var artifact = all.stream().filter(a -> a.id().equals(id)).findFirst().orElseThrow(() -> ProtocolException.invalid("Unknown evidence: " + id));
|
||||
if (!List.of("AVAILABLE", "RETAINED_LEGACY").contains(ArtifactLifecycle.state(root, work, id)))
|
||||
throw ProtocolException.validation("Evidence already retired; attach current inputs for a new evaluation: " + id);
|
||||
validatePayload(Filespace.resolve(works.folder(root, work), artifact.path()), artifact);
|
||||
}
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package net.intrepid.aiengineering.artifact;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.work.Work;
|
||||
import java.util.*;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
/** Only protocol aggregation facts; never arbitrary JSON/file content. */
|
||||
public record ProtocolReceipt(int schemaVersion, String id, String workId, String type, String inputHash,
|
||||
String policyHash, List<Source> sources) {
|
||||
public record Source(String id, Integer revision, String sha256) {
|
||||
public Source {
|
||||
if (revision == null) Work.identifier(id, "WRK");
|
||||
else { Work.identifier(id, "PLN"); if (revision < 1) throw ProtocolException.validation("Invalid receipt source revision"); }
|
||||
digest(sha256);
|
||||
}
|
||||
}
|
||||
private static void digest(String value) {
|
||||
if (value == null || !value.matches("[a-f0-9]{64}")) throw ProtocolException.validation("Invalid receipt digest");
|
||||
}
|
||||
public ProtocolReceipt {
|
||||
ProtocolException.schema(schemaVersion); Work.identifier(id, "ART"); Work.identifier(workId, "WRK"); digest(inputHash);
|
||||
if (!List.of("plans", "epic").contains(type)) throw ProtocolException.validation("Unknown structured receipt type");
|
||||
if (type.equals("epic")) digest(policyHash);
|
||||
else if (policyHash != null) throw ProtocolException.validation("Plan receipt has no EPIC policy");
|
||||
sources = List.copyOf(sources);
|
||||
if (sources.isEmpty() || sources.stream().map(Source::id).distinct().count() != sources.size()) throw ProtocolException.validation("Invalid receipt sources");
|
||||
for (var source : sources) if (type.equals("plans") != (source.revision() != null)) throw ProtocolException.validation("Receipt source type mismatch");
|
||||
}
|
||||
public static ProtocolReceipt from(String id, String work, Object value) {
|
||||
var data = Documents.jsonTree(value); String type = data.has("policyHash") ? "epic" : "plans";
|
||||
var sources = new ArrayList<Source>(); var array = data.get(type.equals("epic") ? "children" : "plans");
|
||||
if (array == null || !array.isArray() || !data.get("workId").stringValue().equals(work)) throw ProtocolException.validation("Invalid structured receipt");
|
||||
for (var source : array) sources.add(type.equals("epic")
|
||||
? new Source(source.get("workId").stringValue(), null, source.get("completionHash").stringValue())
|
||||
: new Source(source.get("id").stringValue(), source.get("revision").intValue(), source.get("sha256").stringValue()));
|
||||
return new ProtocolReceipt(1, id, work, type, data.get("inputHash").stringValue(),
|
||||
type.equals("epic") ? data.get("policyHash").stringValue() : null, sources);
|
||||
}
|
||||
public ObjectNode content() {
|
||||
var data = Documents.jsonTree(Map.of()); data.put("schemaVersion", schemaVersion); data.put("workId", workId);
|
||||
if (type.equals("epic")) data.put("policyHash", policyHash);
|
||||
data.put("inputHash", inputHash);
|
||||
var array = data.putArray(type.equals("epic") ? "children" : "plans");
|
||||
for (var source : sources) {
|
||||
var item = array.addObject();
|
||||
if (type.equals("epic")) { item.put("workId", source.id()); item.put("completionHash", source.sha256()); }
|
||||
else { item.put("id", source.id()); item.put("revision", source.revision()); item.put("sha256", source.sha256()); }
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public final class EngineeringCli implements Runnable {
|
||||
.addSubcommand("decision", new DecisionCommands()).addSubcommand("artifact", new ArtifactCommands())
|
||||
.addSubcommand("plan", new CommandLine(new PlanCommands()).addSubcommand("step", new StepCommands()).addSubcommand("experiment", new ExperimentCommands()))
|
||||
.addSubcommand("topic", new TopicCommands()).addSubcommand("survey", new SurveyCommands()).addSubcommand("agent", new AgentCommands())
|
||||
.addSubcommand("epic", new EpicCommands());
|
||||
.addSubcommand("epic", new EpicCommands()).addSubcommand("gate", new GateCommands()).addSubcommand("storage", new StorageCommands());
|
||||
commandLine.addSubcommand("import", new CommandLine(new ImportCommands()).addSubcommand("discussion", new DiscussionImportCommand()));
|
||||
configure(commandLine, out, err);
|
||||
commandLine.setExecutionExceptionHandler((exception, command, parse) -> {
|
||||
@@ -58,10 +58,59 @@ public final class EngineeringCli implements Runnable {
|
||||
@Override public void run() { commandLine.usage(output); }
|
||||
private Path discoveredRoot() { return projects.discover(cwd, project == null ? null : resolve(project)); }
|
||||
private Path root() {
|
||||
Path root = discoveredRoot(); ProtocolGuide.requireSupportedVersion(root); return root;
|
||||
Path root = discoveredRoot(); StorageMigration.requireStable(root); ProtocolGuide.requireSupportedVersion(root); return root;
|
||||
}
|
||||
private Path resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); }
|
||||
enum Format { markdown, json }
|
||||
@Command(name = "storage", mixinStandardHelpOptions = true, description = "Explicit local storage migration and recovery; never installs native tools.")
|
||||
public class StorageCommands {
|
||||
@Command(name = "migrate", mixinStandardHelpOptions = true, description = "Preview by default. Apply, recover or roll back using the reviewed fingerprint.")
|
||||
int migrate(@Option(names = "--apply") boolean apply, @Option(names = "--recover") boolean recover,
|
||||
@Option(names = "--rollback") boolean rollback, @Option(names = "--expect") String expected,
|
||||
@Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
int actions = (apply ? 1 : 0) + (recover ? 1 : 0) + (rollback ? 1 : 0);
|
||||
if (actions > 1 || (actions == 0 && expected != null) || (actions == 1 && expected == null))
|
||||
throw ProtocolException.invalid("Use preview without flags, or one of --apply/--recover/--rollback with --expect");
|
||||
Path root = discoveredRoot(); var migration = new StorageMigration();
|
||||
var result = apply ? migration.apply(root, expected) : recover || rollback ? migration.recover(root, expected, rollback) : migration.preview(root);
|
||||
emit(result, format); return result.valid() ? 0 : 4;
|
||||
}
|
||||
}
|
||||
@Command(name = "gate", mixinStandardHelpOptions = true, description = "Configure required quality checks and record actual external evaluations.")
|
||||
public class GateCommands {
|
||||
@Command(name = "configure", mixinStandardHelpOptions = true)
|
||||
int configureGate(@Parameters(index = "0") String id,
|
||||
@Option(names = "--work", description = "Additional Work gate; omitted means a required project gate.") String work,
|
||||
@Option(names = "--title", required = true) String title,
|
||||
@Option(names = "--procedure", required = true) String procedure,
|
||||
@Option(names = "--input", required = true, description = "Project-relative file/directory evaluated; repeat for multiple inputs.") List<String> inputs,
|
||||
@Option(names = "--require-evidence") boolean evidence,
|
||||
@Option(names = "--by", required = true) String by,
|
||||
@Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
return emit(new QualityGates().configure(root(), work == null ? "project" : work, id, title, procedure, inputs, evidence, by), format);
|
||||
}
|
||||
@Command(name = "status", mixinStandardHelpOptions = true)
|
||||
int gates(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
return emit(new QualityGates().inspect(root(), work), format);
|
||||
}
|
||||
@Command(name = "history", mixinStandardHelpOptions = true)
|
||||
int gateHistory(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
return emit(new QualityGates().history(root(), work), format);
|
||||
}
|
||||
@Command(name = "record", mixinStandardHelpOptions = true, description = "Record observed evaluation against the fingerprint obtained before running the check.")
|
||||
int recordGate(@Parameters(index = "0") String work, @Parameters(index = "1", description = "project/ID or WRK-ID/ID.") String key,
|
||||
@Option(names = "--expect", required = true) String expected,
|
||||
@Option(names = "--invocation", required = true) String invocation,
|
||||
@Option(names = "--outcome", required = true) QualityGates.Outcome outcome,
|
||||
@Option(names = "--summary", required = true) String summary,
|
||||
@Option(names = "--evidence") List<String> evidence,
|
||||
@Option(names = "--by", required = true) String by,
|
||||
@Option(names = "--observed", description = "Attest this check actually ran; separate from human decision approval.") boolean observed,
|
||||
@Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
var result = new QualityGates().record(root(), work, key, expected, invocation, outcome, summary, safe(evidence), by, observed);
|
||||
afterChange(work, by); return emit(result, format);
|
||||
}
|
||||
}
|
||||
@Command(name = "import", mixinStandardHelpOptions = true, description = "Import supported legacy context with explicit preview and application.")
|
||||
public class ImportCommands implements Runnable {
|
||||
@Override public void run() { commandLine.getSubcommands().get("import").usage(output); }
|
||||
@@ -129,10 +178,13 @@ public final class EngineeringCli implements Runnable {
|
||||
@Option(names = "--name") String name,
|
||||
@Option(names = "--general-adapter", description = "Configure an available adapter without calling it.") String generalAdapter,
|
||||
@Option(names = "--archive-policy", description = "review-only or reversible; requires an executor.") String archivePolicy,
|
||||
@Option(names = "--storage", defaultValue = "sqlite", description = "sqlite (default), or legacy for compatibility fixtures.") String storage,
|
||||
@Option(names = "--version-state", description = "Leave Git ignore policy to the developer; does not untrack or change existing rules.") boolean versionState,
|
||||
@Option(names = "--interactive", description = "Guide project and executor setup before writing files.") boolean interactive,
|
||||
@Option(names = "--input-file", description = "Explicit UTF-8 answers for guided setup.") Path inputFile) {
|
||||
if (project != null && directory != null) throw ProtocolException.invalid("Use a project directory or --project, not both");
|
||||
Path target = project != null ? resolve(project) : directory != null ? resolve(directory) : cwd;
|
||||
if (!List.of("sqlite", "legacy").contains(storage)) throw ProtocolException.invalid("Storage must be sqlite or legacy");
|
||||
boolean guided = interactive || inputFile != null || (name == null && (injectedInput || System.console() != null));
|
||||
if (guided) {
|
||||
if (generalAdapter != null) throw ProtocolException.invalid("Use guided setup or --general-adapter, not both");
|
||||
@@ -140,7 +192,7 @@ public final class EngineeringCli implements Runnable {
|
||||
var reader = inputFile == null ? input : new java.io.StringReader(readDiscussionText(resolve(inputFile)));
|
||||
Path filename = target.toAbsolutePath().normalize().getFileName();
|
||||
var setup = new ProjectSetup(reader, output).collect(name, filename == null ? "Engineering Project" : filename.toString(), archivePolicy);
|
||||
var initialized = projects.initialize(target, setup.name());
|
||||
var initialized = storage.equals("legacy") ? projects.initializeLegacy(target, setup.name()) : projects.initializeSqlite(target, setup.name(), !versionState);
|
||||
if (setup.agents() == null) return emit(initialized, Format.markdown);
|
||||
return emit(projects.configureAgents(projects.discover(target, null), setup.agents()), Format.markdown);
|
||||
}
|
||||
@@ -150,7 +202,7 @@ public final class EngineeringCli implements Runnable {
|
||||
if (new AgentService().available().stream().noneMatch(a -> a.id().equals(generalAdapter))) throw ProtocolException.invalid("Unknown adapter: " + generalAdapter);
|
||||
new ProjectConfig.Agents(new ProjectConfig.Executor(generalAdapter,"general","default"), java.util.Map.of(), archivePolicy == null ? "review-only" : archivePolicy);
|
||||
}
|
||||
var initialized = projects.initialize(target, name);
|
||||
var initialized = storage.equals("legacy") ? projects.initializeLegacy(target, name) : projects.initializeSqlite(target, name, !versionState);
|
||||
if (generalAdapter != null) return emit(new AgentService().configure(projects.discover(target, null), "general", generalAdapter, null, null, archivePolicy), Format.markdown);
|
||||
return emit(initialized, Format.markdown);
|
||||
}
|
||||
@@ -687,6 +739,12 @@ public final class EngineeringCli implements Runnable {
|
||||
}
|
||||
@Command(name = "artifact", mixinStandardHelpOptions = true, description = "Attach small evidence files with integrity metadata.")
|
||||
public class ArtifactCommands {
|
||||
@Command(name = "recover", mixinStandardHelpOptions = true, description = "Recover interrupted temporary publications and retirements; never remove requested outputs.")
|
||||
int recoverArtifacts(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) {
|
||||
Path root = root(); works.load(root, work);
|
||||
int publications = ArtifactPublication.recover(root), retired = ArtifactLifecycle.recover(root, work);
|
||||
return emit(java.util.Map.of("publicationsRecovered", publications, "temporaryPayloadsRetired", retired), format);
|
||||
}
|
||||
@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,
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.util.*;
|
||||
public final class DecisionService {
|
||||
private final WorkService works = new WorkService();
|
||||
private Path path(Path root, String workId, String id) { Work.identifier(id, "DEC"); return Filespace.resolve(works.folder(root, workId), "decisions/" + id + ".md"); }
|
||||
private Decision read(Path path) { return Documents.readMarkdownDocument(path, Decision.class, "text"); }
|
||||
private Decision read(Path path) { return RecordStorage.read(path, Decision.class, "text"); }
|
||||
public List<Decision> list(Path root, String workId) {
|
||||
var work = works.load(root, workId);
|
||||
return work.decisions().stream().map(id -> {
|
||||
@@ -23,7 +23,7 @@ public final class DecisionService {
|
||||
private List<Decision> chain(Path root, Decision current) {
|
||||
var history = new ArrayList<Decision>(); history.add(current); var next = current; Path folder = works.folder(root, current.workId());
|
||||
for (int revision = current.revision() - 1; revision >= 1; revision--) {
|
||||
Path path = Revisions.history(folder, "decisions", current.id(), revision); String original = Filespace.read(path);
|
||||
Path path = Revisions.history(folder, "decisions", current.id(), revision); String original = RecordStorage.raw(path, Decision.class, "text");
|
||||
Revisions.chain(next.revision(), next.previousHash(), revision + 1, original);
|
||||
var prior = read(path); identity(prior, current.workId(), current.id());
|
||||
if (prior.revision() != revision) throw ProtocolException.validation("Invalid decision history revision: " + path);
|
||||
@@ -45,7 +45,7 @@ public final class DecisionService {
|
||||
if (work.guidance() != null) work.guidance().requireDecisionRequest(id);
|
||||
var decision = new Decision(1, id, workId, title, context, approach, List.of(), rationale, List.of(), List.of(), Decision.Status.DRAFT,
|
||||
author, now, evidence, text, 1, null, now, author, "Draft created", List.of(), null, null);
|
||||
Documents.writeMarkdownDocument(path(root, workId, id), decision, "text", false); works.addReference(root, workId, "decisions", id); return decision;
|
||||
RecordStorage.write(path(root, workId, id), decision, Decision.class, "text", false); works.addReference(root, workId, "decisions", id); return decision;
|
||||
});
|
||||
}
|
||||
private void evidence(Work work, List<String> references) {
|
||||
@@ -53,24 +53,24 @@ public final class DecisionService {
|
||||
}
|
||||
private Decision publish(Path root, Decision old, Decision changed, String original) {
|
||||
if (changed.equals(old)) return old;
|
||||
Revisions.replace(works.folder(root, old.workId()), "decisions", old.id(), old.revision(), original, Documents.markdownDocument(changed, "text"));
|
||||
RecordStorage.replaceRevision(works.folder(root, old.workId()), "decisions", old.id(), old.revision(), original, Documents.markdownDocument(changed, "text"), Decision.class, "text");
|
||||
works.touched(root, old.workId(), changed.updatedAt()); return changed;
|
||||
}
|
||||
public Decision update(Path root, String workId, String id, Decision.Update value, String by, String reason) {
|
||||
return Filespace.locked(root, () -> {
|
||||
var work = works.editable(root, workId); var old = get(root, workId, id); String original = Filespace.read(path(root, workId, id));
|
||||
var work = works.editable(root, workId); var old = get(root, workId, id); String original = RecordStorage.raw(path(root, workId, id), Decision.class, "text");
|
||||
var changed = old.update(value, by, reason, Revisions.hash(original)); evidence(work, changed.evidence()); return publish(root, old, changed, original);
|
||||
});
|
||||
}
|
||||
public Decision accept(Path root, String workId, String id, String by, String reason, boolean humanApproved) {
|
||||
return Filespace.locked(root, () -> {
|
||||
works.editable(root, workId); var old = get(root, workId, id); String original = Filespace.read(path(root, workId, id));
|
||||
works.editable(root, workId); var old = get(root, workId, id); String original = RecordStorage.raw(path(root, workId, id), Decision.class, "text");
|
||||
var accepted = old.accept(by, reason, humanApproved, Revisions.hash(original)); Decision parent = null; String parentOriginal = null;
|
||||
if (old.revises() != null) {
|
||||
parent = get(root, workId, old.revises());
|
||||
if (parent.approvalStatus() != Decision.Status.ACCEPTED && parent.approvalStatus() != Decision.Status.REJECTED)
|
||||
throw ProtocolException.invalid("The revised decision has already been superseded");
|
||||
parentOriginal = Filespace.read(path(root, workId, parent.id()));
|
||||
parentOriginal = RecordStorage.raw(path(root, workId, parent.id()), Decision.class, "text");
|
||||
}
|
||||
publish(root, old, accepted, original);
|
||||
if (parent != null && parent.approvalStatus() == Decision.Status.ACCEPTED)
|
||||
@@ -87,10 +87,14 @@ public final class DecisionService {
|
||||
public void publish(Path folder) {
|
||||
for (var change : changes) {
|
||||
attempted.add(change);
|
||||
Revisions.replace(folder, "decisions", change.old().id(), change.old().revision(), change.original(), change.replacement());
|
||||
RecordStorage.replaceRevision(folder, "decisions", change.old().id(), change.old().revision(), change.original(), change.replacement(), Decision.class, "text");
|
||||
}
|
||||
}
|
||||
public void rollback() {
|
||||
if (!changes.isEmpty()) {
|
||||
Path root = RecordStorage.sqliteRoot(changes.getFirst().current());
|
||||
if (root != null) { SqliteDatabase.rollbackOnly(root); return; }
|
||||
}
|
||||
for (var change : attempted.reversed()) {
|
||||
String current = Filespace.read(change.current());
|
||||
if (!current.equals(change.original()) && !current.equals(change.replacement()))
|
||||
@@ -119,7 +123,7 @@ public final class DecisionService {
|
||||
if (!work.guidance().waived()) throw ProtocolException.invalid("Human approval is required for " + old.id() + "; creating a Plan cannot bypass it");
|
||||
}
|
||||
evidence(work, old.evidence());
|
||||
String original = Filespace.read(path(root, workId, old.id())); originals.put(old.id(), original);
|
||||
String original = RecordStorage.raw(path(root, workId, old.id()), Decision.class, "text"); originals.put(old.id(), original);
|
||||
proposed.put(old.id(), old.acceptForPlan(plan, requester, Revisions.hash(original)));
|
||||
if (old.revises() != null) {
|
||||
var parent = get(root, workId, old.revises());
|
||||
@@ -127,7 +131,7 @@ public final class DecisionService {
|
||||
throw ProtocolException.invalid("The revised decision has already been superseded");
|
||||
if (parent.approvalStatus() == Decision.Status.ACCEPTED) {
|
||||
if (proposed.containsKey(parent.id())) throw ProtocolException.invalid("Conflicting decision replacements in Plan: " + parent.id());
|
||||
String parentOriginal = Filespace.read(path(root, workId, parent.id())); originals.put(parent.id(), parentOriginal);
|
||||
String parentOriginal = RecordStorage.raw(path(root, workId, parent.id()), Decision.class, "text"); originals.put(parent.id(), parentOriginal);
|
||||
proposed.put(parent.id(), parent.supersedeForPlan(old.id(), plan, requester, Revisions.hash(parentOriginal)));
|
||||
}
|
||||
}
|
||||
@@ -140,14 +144,14 @@ public final class DecisionService {
|
||||
var old = get(root, workId, next.id()); String original = originals.get(next.id());
|
||||
Path current = path(root, workId, old.id()), history = Revisions.history(folder, "decisions", old.id(), old.revision());
|
||||
boolean exists = Files.exists(history);
|
||||
if (exists && !Filespace.read(history).equals(original)) throw ProtocolException.validation("Conflicting revision history: " + history);
|
||||
if (exists && !RecordStorage.raw(history, Decision.class, "text").equals(original)) throw ProtocolException.validation("Conflicting revision history: " + history);
|
||||
changes.add(new PlanChange(old, next, original, Documents.markdownDocument(next, "text"), current, history, exists));
|
||||
}
|
||||
return new PlanAcceptance(changes);
|
||||
}
|
||||
public Decision reject(Path root, String workId, String id, String by, String reason) {
|
||||
return Filespace.locked(root, () -> {
|
||||
works.editable(root, workId); var old = get(root, workId, id); String original = Filespace.read(path(root, workId, id));
|
||||
works.editable(root, workId); var old = get(root, workId, id); String original = RecordStorage.raw(path(root, workId, id), Decision.class, "text");
|
||||
return publish(root, old, old.reject(by, reason, Revisions.hash(original)), original);
|
||||
});
|
||||
}
|
||||
@@ -161,7 +165,7 @@ public final class DecisionService {
|
||||
if (work.guidance() != null) work.guidance().requireDecisionRequest(next);
|
||||
var draft = new Decision(1, next, workId, old.title(), old.context(), old.approach(), old.alternatives(), old.rationale(), old.risks(), old.acceptanceCriteria(),
|
||||
Decision.Status.DRAFT, by, now, old.evidence(), old.text(), 1, null, now, by, reason, List.of(), id, null);
|
||||
Documents.writeMarkdownDocument(path(root, workId, next), draft, "text", false); works.addReference(root, workId, "decisions", next); return draft;
|
||||
RecordStorage.write(path(root, workId, next), draft, Decision.class, "text", false); works.addReference(root, workId, "decisions", next); return draft;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,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.readMarkdownDocument(Filespace.resolve(folder, "discussions/" + ref + ".md"), DiscussionEntry.class, "text");
|
||||
var entry = RecordStorage.read(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();
|
||||
@@ -38,7 +38,7 @@ public final class DiscussionService {
|
||||
public DiscussionEntry writePrepared(Path folder, String workId, String id, String text, DiscussionEntry.Kind kind,
|
||||
String author, String discussionId, String respondsTo) {
|
||||
var entry = new DiscussionEntry(1, id, workId, discussionId, kind, author, Instant.now().toString(), respondsTo, text);
|
||||
Documents.writeMarkdownDocument(Filespace.resolve(folder, "discussions/" + id + ".md"), entry, "text", false); return entry;
|
||||
RecordStorage.write(Filespace.resolve(folder, "discussions/" + id + ".md"), entry, DiscussionEntry.class, "text", false); return entry;
|
||||
}
|
||||
public record MigrationReport(int schemaVersion, int converted, int unchanged, List<String> backups) {
|
||||
public MigrationReport { backups = List.copyOf(backups); }
|
||||
@@ -46,6 +46,7 @@ public final class DiscussionService {
|
||||
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) {
|
||||
if (SqliteDatabase.active(root)) return new MigrationReport(1, 0, list(root, workId).size(), List.of());
|
||||
return Filespace.locked(root, () -> {
|
||||
var entries = list(root, workId); var conversions = new java.util.ArrayList<Conversion>();
|
||||
Path folder = works.folder(root, workId);
|
||||
|
||||
@@ -17,7 +17,7 @@ public final class DispositionService {
|
||||
var w=works.load(root,work); var result=new ArrayList<Disposition>(); var archived=new HashSet<String>();
|
||||
var entries=new DiscussionService().list(root,work);
|
||||
for(String id:w.dispositions()) {
|
||||
var d=Documents.readMarkdownDocument(Filespace.resolve(works.folder(root,work),"dispositions/"+id+".md"),Disposition.class,"reason");
|
||||
var d=RecordStorage.read(Filespace.resolve(works.folder(root,work),"dispositions/"+id+".md"),Disposition.class,"reason");
|
||||
if(!id.equals(d.id())||!work.equals(d.workId())||!w.discussions().contains(d.entryId())||!w.artifacts().containsAll(d.evidence())) throw ProtocolException.validation("Invalid disposition references: "+id);
|
||||
if(entries.stream().noneMatch(e->e.id().equals(d.entryId())&&eligible(e))) throw ProtocolException.validation("Invalid disposition target: "+id);
|
||||
boolean changed=d.action()==Disposition.Action.ARCHIVE?archived.add(d.entryId()):archived.remove(d.entryId());
|
||||
@@ -38,6 +38,7 @@ public final class DispositionService {
|
||||
if(config==null||!config.archivePolicy().equals("reversible")) throw ProtocolException.invalid("Archive policy is review-only; configure reversible explicitly");
|
||||
if(evidence.isEmpty()) throw ProtocolException.invalid("Archive requires evidence");
|
||||
new ArtifactService().validate(root,work);
|
||||
new ArtifactService().requireAvailable(root,work,evidence);
|
||||
}
|
||||
if(archived(root,work,entry)==(action==Disposition.Action.ARCHIVE)) throw ProtocolException.invalid("Proposal is already in the requested state");
|
||||
}
|
||||
@@ -46,7 +47,7 @@ public final class DispositionService {
|
||||
var w=works.editable(root,work); check(root,work,entry,action,evidence);
|
||||
var d=new Disposition(1,works.nextReference(w.dispositions(),"DSP"),work,entry,action,reason,evidence,by,Instant.now().toString());
|
||||
var p=Filespace.resolve(works.folder(root,work),"dispositions/"+d.id()+".md"); Filespace.directory(p.getParent());
|
||||
Documents.writeMarkdownDocument(p,d,"reason",false); works.addReference(root,work,"dispositions",d.id()); return d;
|
||||
RecordStorage.write(p,d,Disposition.class,"reason",false); works.addReference(root,work,"dispositions",d.id()); return d;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.util.*;
|
||||
public final class SurveyService {
|
||||
private final WorkService works = new WorkService();
|
||||
private Path path(Path root, String work, String id) { Work.identifier(id, "SVY"); return Filespace.resolve(works.folder(root, work), "surveys/" + id + ".md"); }
|
||||
private Survey read(Path path) { return Documents.readMarkdownDocument(path, Survey.class, "description"); }
|
||||
private Survey read(Path path) { return RecordStorage.read(path, Survey.class, "description"); }
|
||||
private void identity(Survey value, String work, String id) {
|
||||
if (!value.id().equals(id) || !value.workId().equals(work)) throw ProtocolException.validation("Survey identity mismatch: " + id);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public final class SurveyService {
|
||||
private List<Survey> chain(Path root, Survey current) {
|
||||
var all = new ArrayList<Survey>(); all.add(current); var next = current;
|
||||
for (int revision = current.revision() - 1; revision >= 1; revision--) {
|
||||
Path p = Revisions.history(works.folder(root, current.workId()), "surveys", current.id(), revision); String raw = Filespace.read(p);
|
||||
Path p = Revisions.history(works.folder(root, current.workId()), "surveys", current.id(), revision); String raw = RecordStorage.raw(p, Survey.class, "description");
|
||||
Revisions.chain(next.revision(), next.previousHash(), revision + 1, raw);
|
||||
var previous = read(p); identity(previous, current.workId(), current.id());
|
||||
if (previous.revision() != revision) throw ProtocolException.validation("Invalid survey history revision");
|
||||
@@ -43,12 +43,12 @@ public final class SurveyService {
|
||||
return Filespace.locked(root, () -> {
|
||||
var w = works.editable(root, work); String id = works.nextReference(w.surveys(), "SVY"), now = Instant.now().toString();
|
||||
var survey = new Survey(1, id, work, title, description, List.of(), List.of(), author, now, 1, null, now, author, "Survey created");
|
||||
var p = path(root, work, id); Filespace.directory(p.getParent()); Documents.writeMarkdownDocument(p, survey, "description", false);
|
||||
var p = path(root, work, id); Filespace.directory(p.getParent()); RecordStorage.write(p, survey, Survey.class, "description", false);
|
||||
works.addReference(root, work, "surveys", id); return survey;
|
||||
});
|
||||
}
|
||||
private Survey publish(Path root, Survey old, Survey changed, String raw) {
|
||||
Revisions.replace(works.folder(root, old.workId()), "surveys", old.id(), old.revision(), raw, Documents.markdownDocument(changed, "description"));
|
||||
RecordStorage.replaceRevision(works.folder(root, old.workId()), "surveys", old.id(), old.revision(), raw, Documents.markdownDocument(changed, "description"), Survey.class, "description");
|
||||
works.touched(root, old.workId(), changed.updatedAt()); return changed;
|
||||
}
|
||||
public Survey question(Path root, String work, String id, String topic, String text, List<String> options,
|
||||
@@ -58,7 +58,7 @@ public final class SurveyService {
|
||||
if (!w.discussions().containsAll(sources)) throw ProtocolException.invalid("Unknown question source");
|
||||
var choices = new ArrayList<Survey.Option>(); for (int i=0;i<options.size();i++) choices.add(new Survey.Option(""+(i+1), options.get(i)));
|
||||
var question = new Survey.Question(works.nextReference(old.questions().stream().map(Survey.Question::id).toList(), "QST"), topic, text, choices, multiple, recommend, sources);
|
||||
var questions = new ArrayList<>(old.questions()); questions.add(question); String raw = Filespace.read(path(root, work, id));
|
||||
var questions = new ArrayList<>(old.questions()); questions.add(question); String raw = RecordStorage.raw(path(root, work, id), Survey.class, "description");
|
||||
return publish(root, old, old.changed(questions, old.answers(), by, "Question added", Revisions.hash(raw)), raw);
|
||||
});
|
||||
}
|
||||
@@ -69,7 +69,7 @@ public final class SurveyService {
|
||||
var latest = old.latest(questionId);
|
||||
var answer = new Survey.Answer(works.nextReference(old.answers().stream().map(Survey.Answer::id).toList(), "ANS"), questionId,
|
||||
choices, text == null ? "" : text, author, Instant.now().toString(), latest == null ? null : latest.id());
|
||||
var answers = new ArrayList<>(old.answers()); answers.add(answer); String raw = Filespace.read(path(root, work, id));
|
||||
var answers = new ArrayList<>(old.answers()); answers.add(answer); String raw = RecordStorage.raw(path(root, work, id), Survey.class, "description");
|
||||
return publish(root, old, old.changed(old.questions(), answers, author, latest == null ? "Answer recorded" : "Answer revised; related conclusions may need review", Revisions.hash(raw)), raw);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ public final class TopicService {
|
||||
public View { sources = List.copyOf(sources); }
|
||||
}
|
||||
private Path path(Path root, String work, String id) { Work.identifier(id, "TOP"); return Filespace.resolve(works.folder(root, work), "topics/" + id + ".md"); }
|
||||
private Topic read(Path path) { return Documents.readMarkdownDocument(path, Topic.class, "description"); }
|
||||
private Topic read(Path path) { return RecordStorage.read(path, Topic.class, "description"); }
|
||||
private void identity(Topic t, String work, String id) {
|
||||
if (!t.workId().equals(work) || !t.id().equals(id)) throw ProtocolException.validation("Topic identity mismatch: " + id);
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public final class TopicService {
|
||||
private List<Topic> chain(Path root, Topic current) {
|
||||
var all = new ArrayList<Topic>(); all.add(current); var next = current;
|
||||
for (int revision = current.revision() - 1; revision >= 1; revision--) {
|
||||
var p = Revisions.history(works.folder(root, current.workId()), "topics", current.id(), revision); String raw = Filespace.read(p);
|
||||
var p = Revisions.history(works.folder(root, current.workId()), "topics", current.id(), revision); String raw = RecordStorage.raw(p, Topic.class, "description");
|
||||
Revisions.chain(next.revision(), next.previousHash(), revision + 1, raw);
|
||||
var previous = read(p); identity(previous, current.workId(), current.id());
|
||||
if (previous.revision() != revision) throw ProtocolException.validation("Invalid topic history revision");
|
||||
@@ -59,19 +59,19 @@ public final class TopicService {
|
||||
if (!w.discussions().containsAll(sources)) throw ProtocolException.invalid("Unknown topic source");
|
||||
String id = works.nextReference(w.topics(), "TOP"), now = Instant.now().toString();
|
||||
var topic = new Topic(1, id, work, title, description, sources, author, now, 1, null, now, author, "Topic created");
|
||||
var p = path(root, work, id); Filespace.directory(p.getParent()); Documents.writeMarkdownDocument(p, topic, "description", false);
|
||||
var p = path(root, work, id); Filespace.directory(p.getParent()); RecordStorage.write(p, topic, Topic.class, "description", false);
|
||||
works.addReference(root, work, "topics", id); return topic;
|
||||
});
|
||||
}
|
||||
public Topic update(Path root, String work, String id, String title, String description, String by, String reason) {
|
||||
if (title == null && description == null) throw ProtocolException.invalid("Specify a topic field to update");
|
||||
return Filespace.locked(root, () -> {
|
||||
works.editable(root, work); var old = get(root, work, id); String raw = Filespace.read(path(root, work, id));
|
||||
works.editable(root, work); var old = get(root, work, id); String raw = RecordStorage.raw(path(root, work, id), Topic.class, "description");
|
||||
String nextTitle = title == null ? old.title() : title, nextDescription = description == null ? old.description() : description;
|
||||
if (nextTitle.equals(old.title()) && nextDescription.equals(old.description())) return old;
|
||||
var changed = new Topic(1, id, work, nextTitle, nextDescription, old.sources(), old.author(), old.createdAt(), old.revision() + 1,
|
||||
Revisions.hash(raw), Instant.now().toString(), by, reason);
|
||||
Revisions.replace(works.folder(root, work), "topics", id, old.revision(), raw, Documents.markdownDocument(changed, "description"));
|
||||
RecordStorage.replaceRevision(works.folder(root, work), "topics", id, old.revision(), raw, Documents.markdownDocument(changed, "description"), Topic.class, "description");
|
||||
works.touched(root, work, changed.updatedAt()); return changed;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,6 +21,11 @@ public final class Documents {
|
||||
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 ObjectNode jsonTree(Object value) { return JSON.valueToTree(value); }
|
||||
public static <T> T jsonValue(ObjectNode value, Class<T> type) {
|
||||
try { return JSON.treeToValue(value, type); }
|
||||
catch (RuntimeException e) { throw ProtocolException.validation("Invalid " + type.getSimpleName() + ": " + e.getMessage()); }
|
||||
}
|
||||
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()); }
|
||||
@@ -39,7 +44,13 @@ public final class Documents {
|
||||
}
|
||||
/** 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);
|
||||
return parseMarkdownDocument(Filespace.read(path), type, bodyField, path);
|
||||
}
|
||||
public static <T> T parseMarkdownDocument(String content, Class<T> type, String bodyField) {
|
||||
return parseMarkdownDocument(content, type, bodyField, Path.of("captured-record.md"));
|
||||
}
|
||||
private static <T> T parseMarkdownDocument(String content, Class<T> type, String bodyField, Path path) {
|
||||
var parts = parts(content, path.toString());
|
||||
int version = version(parts.metadata(), path);
|
||||
parts.metadata().remove("documentVersion");
|
||||
if (version == 2) {
|
||||
|
||||
@@ -66,11 +66,28 @@ public final class Filespace {
|
||||
});
|
||||
}
|
||||
public static <T> T locked(Path projectRoot, Supplier<T> operation) {
|
||||
boolean sqlite = SqliteDatabase.active(projectRoot);
|
||||
String transition = transition(projectRoot);
|
||||
return lockedFile(projectRoot, () -> {
|
||||
if (sqlite != SqliteDatabase.active(projectRoot) || !transition.equals(transition(projectRoot)))
|
||||
throw ProtocolException.validation("Project storage changed while waiting; inspect migration and retry the command");
|
||||
return sqlite ? SqliteDatabase.write(projectRoot, connection -> operation.get()) : operation.get();
|
||||
}, sqlite);
|
||||
}
|
||||
private static String transition(Path root) {
|
||||
Path journal = resolve(root, ".ai-engineering/.local/sqlite-migration/state.json");
|
||||
return Files.exists(journal) ? read(journal) : "";
|
||||
}
|
||||
/** Explicit bootstrap/migration lock, also usable before a database becomes authoritative. */
|
||||
public static <T> T lockedLegacy(Path projectRoot, Supplier<T> operation) {
|
||||
return lockedFile(projectRoot, operation, false);
|
||||
}
|
||||
private static <T> T lockedFile(Path projectRoot, Supplier<T> operation, boolean bounded) {
|
||||
Path lock = resolve(projectRoot, ".ai-engineering/.local/write.lock");
|
||||
if (HELD.get().contains(lock)) return operation.get();
|
||||
directory(lock.getParent());
|
||||
return io(() -> {
|
||||
try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = channel.lock()) {
|
||||
try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = acquire(channel, bounded)) {
|
||||
HELD.get().add(lock);
|
||||
try { return operation.get(); }
|
||||
finally { HELD.get().remove(lock); if (HELD.get().isEmpty()) HELD.remove(); }
|
||||
@@ -79,6 +96,17 @@ public final class Filespace {
|
||||
}
|
||||
});
|
||||
}
|
||||
private static java.nio.channels.FileLock acquire(FileChannel channel, boolean bounded) throws IOException {
|
||||
if (!bounded) return channel.lock();
|
||||
long deadline = System.nanoTime() + SqliteDatabase.DEFAULT_BUSY_MILLIS * 1_000_000L;
|
||||
do {
|
||||
try { var lock = channel.tryLock(); if (lock != null) return lock; }
|
||||
catch (java.nio.channels.OverlappingFileLockException busy) { /* Another local command is publishing. */ }
|
||||
try { Thread.sleep(10); }
|
||||
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw ProtocolException.validation("Interrupted while waiting for the storage publication lock"); }
|
||||
} while (System.nanoTime() < deadline);
|
||||
throw ProtocolException.validation("Project storage publication is busy after a wait limited to " + SqliteDatabase.DEFAULT_BUSY_MILLIS + " ms; retry after migration or the other command finishes");
|
||||
}
|
||||
public static void moveDirectory(Path from, Path to) {
|
||||
io(() -> {
|
||||
if (Files.exists(to, NOFOLLOW_LINKS)) throw ProtocolException.invalid("Already exists: " + to);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Explicit domain record adapter. File serialization remains the legacy/bootstrap codec. */
|
||||
public final class RecordStorage {
|
||||
private RecordStorage() {}
|
||||
private record Key(Path root, String work, String kind, String id, int revision) {}
|
||||
private static final Pattern WORK_FOLDER = Pattern.compile("(WRK-[0-9A-F]{4,9})-.+");
|
||||
private static final Map<String, String> AREAS = Map.of("discussions", "discussion", "topics", "topic",
|
||||
"surveys", "survey", "dispositions", "disposition", "decisions", "decision", "plans", "plan",
|
||||
"epic", "epic", "agent-runs", "run");
|
||||
public static Path sqliteRoot(Path inside) {
|
||||
for (Path current = inside.toAbsolutePath().normalize(); current != null; current = current.getParent())
|
||||
if (current.getFileName() != null && current.getFileName().toString().equals(".ai-engineering"))
|
||||
return SqliteDatabase.active(current.getParent()) ? current.getParent() : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Key key(Path path) {
|
||||
Path absolute = path.toAbsolutePath().normalize();
|
||||
Path workspace = absolute.getParent();
|
||||
while (workspace != null && (workspace.getFileName() == null || !workspace.getFileName().toString().equals(".ai-engineering"))) workspace = workspace.getParent();
|
||||
if (workspace == null) return null;
|
||||
Path root = workspace.getParent();
|
||||
Path relative = workspace.relativize(absolute);
|
||||
if (relative.getNameCount() < 3 || !relative.getName(0).toString().equals("works") || !SqliteDatabase.active(root)) return null;
|
||||
var match = WORK_FOLDER.matcher(relative.getName(1).toString());
|
||||
if (!match.matches()) return null;
|
||||
String work = match.group(1), kind, id; int revision = 0;
|
||||
if (relative.getNameCount() == 3 && relative.getName(2).toString().equals("work.md")) { kind = "work"; id = work; }
|
||||
else if (relative.getNameCount() == 4 && AREAS.containsKey(relative.getName(2).toString())) {
|
||||
kind = AREAS.get(relative.getName(2).toString()); id = relative.getFileName().toString().replaceFirst("\\.md$", "");
|
||||
} else if (relative.getNameCount() == 6 && AREAS.containsKey(relative.getName(2).toString())
|
||||
&& relative.getName(3).toString().equals(".history") && relative.getFileName().toString().matches("r[0-9]{4,9}\\.md")) {
|
||||
kind = AREAS.get(relative.getName(2).toString()); id = relative.getName(4).toString();
|
||||
revision = Integer.parseInt(relative.getFileName().toString().substring(1).replace(".md", ""));
|
||||
} else return null;
|
||||
String folder = SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT folder FROM work_location WHERE work_id=?")) {
|
||||
statement.setString(1, work);
|
||||
try (var rows = statement.executeQuery()) {
|
||||
if (!rows.next()) throw ProtocolException.missing("Work location not found: " + work);
|
||||
return rows.getString(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!folder.equals(relative.getName(1).toString())) throw ProtocolException.validation("Work directory/identity mismatch: " + path);
|
||||
return new Key(root, work, kind, id, revision);
|
||||
}
|
||||
|
||||
public static <T> T read(Path path, Class<T> type, String bodyField) {
|
||||
var key = key(path);
|
||||
return key == null ? Documents.readMarkdownDocument(path, type, bodyField)
|
||||
: SqliteRecords.get(key.root(), key.work(), key.kind(), key.id(), key.revision(), type);
|
||||
}
|
||||
public static <T> void write(Path path, T value, Class<T> type, String bodyField, boolean replace) {
|
||||
var key = key(path);
|
||||
if (key == null) {
|
||||
if (bodyField == null) Documents.writeDocument(path, value, replace);
|
||||
else Documents.writeMarkdownDocument(path, value, bodyField, replace);
|
||||
} else SqliteRecords.put(key.root(), key.work(), key.kind(), key.id(), value, type, replace, bodyField == null ? 1 : 2);
|
||||
}
|
||||
public static <T> String raw(Path path, Class<T> type, String bodyField) {
|
||||
var key = key(path);
|
||||
return key == null ? Filespace.read(path)
|
||||
: SqliteRecords.raw(key.root(), key.work(), key.kind(), key.id(), key.revision(), type, bodyField);
|
||||
}
|
||||
public static <T> void frontMatter(Path path, T value, Class<T> type) {
|
||||
if (key(path) == null) Documents.replaceFrontMatter(path, value);
|
||||
else write(path, value, type, null, true);
|
||||
}
|
||||
public static <T> void replaceRevision(Path folder, String area, String id, int revision,
|
||||
String original, String replacement, Class<T> type, String bodyField) {
|
||||
Path current = Filespace.resolve(folder, area + "/" + id + ".md");
|
||||
var key = key(current);
|
||||
if (key == null) { Revisions.replace(folder, area, id, revision, original, replacement); return; }
|
||||
SqliteDatabase.write(key.root(), connection -> {
|
||||
if (SqliteRecords.current(key.root(), key.work(), key.kind(), id) != revision
|
||||
|| !raw(current, type, bodyField).equals(original)) throw ProtocolException.validation("Concurrent record edit: " + id);
|
||||
T changed = Documents.parseMarkdownDocument(replacement, type, bodyField);
|
||||
var tree = Documents.jsonTree(changed);
|
||||
if (tree.get("revision").intValue() != revision + 1) throw ProtocolException.validation("Invalid replacement revision: " + id);
|
||||
var metadata = Documents.metadataText(replacement);
|
||||
int version = metadata.has("documentVersion") ? metadata.get("documentVersion").intValue() : 1;
|
||||
SqliteRecords.put(key.root(), key.work(), key.kind(), id, changed, type, true, version);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import org.sqlite.JDBC;
|
||||
|
||||
/** Explicit local database lifecycle and command-scoped transactions; no project discovery or migration. */
|
||||
public final class SqliteDatabase {
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
public static final int APPLICATION_ID = 0x41494531;
|
||||
public static final int DEFAULT_BUSY_MILLIS = 2000;
|
||||
private static final ThreadLocal<Map<Path, Session>> SESSIONS = ThreadLocal.withInitial(HashMap::new);
|
||||
private SqliteDatabase() {}
|
||||
|
||||
@FunctionalInterface public interface Operation<T> { T run(Connection connection) throws SQLException; }
|
||||
private static final class Session {
|
||||
final Connection connection;
|
||||
final boolean write;
|
||||
boolean rollbackOnly;
|
||||
final List<Runnable> committed = new ArrayList<>();
|
||||
final List<Runnable> rolledBack = new ArrayList<>();
|
||||
Session(Connection connection, boolean write) { this.connection = connection; this.write = write; }
|
||||
}
|
||||
|
||||
public static Path path(Path root) { return Filespace.resolve(root, ".ai-engineering/aie.db"); }
|
||||
|
||||
public static boolean active(Path root) {
|
||||
Path config = Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml");
|
||||
if (!Files.isRegularFile(config, LinkOption.NOFOLLOW_LINKS)) return false;
|
||||
var node = Documents.read(config, tools.jackson.databind.node.ObjectNode.class).get("storage");
|
||||
if (node == null || node.isNull()) return false;
|
||||
if (!node.isString() || !node.stringValue().equals("sqlite")) throw ProtocolException.validation("Unsupported project storage");
|
||||
Path manifest = Filespace.resolve(root, ".ai-engineering/protocol.json");
|
||||
if (!Files.isRegularFile(manifest, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.validation("SQLite storage requires protocol contract 4; inspect compatibility with a compatible CLI");
|
||||
var version = Documents.readJson(manifest, tools.jackson.databind.node.ObjectNode.class).get("protocolVersion");
|
||||
if (version == null || !version.isIntegralNumber() || version.intValue() != 4)
|
||||
throw ProtocolException.validation("SQLite storage requires supported protocol contract 4; inspect compatibility before writing");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Path checked(Path root) {
|
||||
Path path = path(root);
|
||||
for (String suffix : List.of("-wal", "-shm", "-journal")) {
|
||||
Path sidecar = Filespace.resolve(root, ".ai-engineering/aie.db" + suffix);
|
||||
if (Files.exists(sidecar, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(sidecar, LinkOption.NOFOLLOW_LINKS))
|
||||
throw ProtocolException.validation("SQLite sidecar must be a regular file: " + sidecar);
|
||||
}
|
||||
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
|
||||
throw ProtocolException.validation("AIE database must be a regular file: " + path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/** A separate, explicit operation. Opening a missing database never creates one. */
|
||||
public static void initialize(Path root) {
|
||||
Path path = checked(root);
|
||||
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS))
|
||||
throw ProtocolException.invalid("Database already exists; initialization cannot replace it: " + path);
|
||||
for (String suffix : List.of("-wal", "-shm", "-journal"))
|
||||
if (Files.exists(path.resolveSibling("aie.db" + suffix), LinkOption.NOFOLLOW_LINKS))
|
||||
throw ProtocolException.validation("Existing SQLite sidecar requires inspection before initialization");
|
||||
Filespace.directory(path.getParent());
|
||||
Filespace.io(() -> { Files.createFile(path); return null; });
|
||||
boolean complete = false;
|
||||
try (var connection = connect(path, true, DEFAULT_BUSY_MILLIS)) {
|
||||
try (var statement = connection.createStatement()) {
|
||||
statement.execute("PRAGMA journal_mode=WAL");
|
||||
statement.execute("PRAGMA synchronous=FULL");
|
||||
}
|
||||
connection.setAutoCommit(false);
|
||||
try (var statement = connection.createStatement()) {
|
||||
String schema = Filespace.io(() -> {
|
||||
try (var input = SqliteDatabase.class.getResourceAsStream("/sqlite/schema-v1.sql")) {
|
||||
if (input == null) throw ProtocolException.validation("Missing SQLite schema resource");
|
||||
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
});
|
||||
for (String sql : schema.split(";")) if (!sql.isBlank()) statement.execute(sql);
|
||||
statement.execute("PRAGMA application_id=" + APPLICATION_ID);
|
||||
statement.execute("PRAGMA user_version=" + SCHEMA_VERSION);
|
||||
connection.commit();
|
||||
complete = true;
|
||||
} catch (SQLException | RuntimeException failure) {
|
||||
rollback(connection, failure); throw failure;
|
||||
}
|
||||
} catch (SQLException failure) { throw problem(failure, DEFAULT_BUSY_MILLIS); }
|
||||
finally {
|
||||
if (!complete) Filespace.io(() -> {
|
||||
for (String suffix : List.of("", "-wal", "-shm", "-journal"))
|
||||
Files.deleteIfExists(Filespace.resolve(root, ".ai-engineering/aie.db" + suffix));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T read(Path root, Operation<T> operation) {
|
||||
return transaction(root, false, DEFAULT_BUSY_MILLIS, operation);
|
||||
}
|
||||
public static void checkpoint(Path root) {
|
||||
Path path = checked(root);
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.missing("Missing AIE database: " + path);
|
||||
if (SESSIONS.get().containsKey(path)) throw ProtocolException.invalid("Checkpoint requires closed command transactions");
|
||||
try (var connection = connect(path, true, DEFAULT_BUSY_MILLIS)) {
|
||||
validate(connection);
|
||||
try (var statement = connection.createStatement(); var row = statement.executeQuery("PRAGMA wal_checkpoint(TRUNCATE)")) {
|
||||
if (!row.next() || row.getInt(1) != 0) throw ProtocolException.validation("Database checkpoint is busy; retry migration after other commands finish");
|
||||
}
|
||||
} catch (SQLException failure) { throw problem(failure, DEFAULT_BUSY_MILLIS); }
|
||||
}
|
||||
public static void rollbackOnly(Path root) {
|
||||
var session = SESSIONS.get().get(path(root));
|
||||
if (session == null || !session.write) throw ProtocolException.invalid("No active SQLite write transaction to roll back");
|
||||
session.rollbackOnly = true;
|
||||
}
|
||||
public static void afterCommit(Path root, Runnable operation) { callbacks(root).committed.add(operation); }
|
||||
public static void afterRollback(Path root, Runnable operation) { callbacks(root).rolledBack.add(operation); }
|
||||
private static Session callbacks(Path root) {
|
||||
var session = SESSIONS.get().get(path(root));
|
||||
if (session == null || !session.write) throw ProtocolException.invalid("File publication requires an active SQLite write transaction");
|
||||
return session;
|
||||
}
|
||||
public static <T> T write(Path root, Operation<T> operation) {
|
||||
return transaction(root, true, DEFAULT_BUSY_MILLIS, operation);
|
||||
}
|
||||
public static <T> T write(Path root, int busyMillis, Operation<T> operation) {
|
||||
return transaction(root, true, busyMillis, operation);
|
||||
}
|
||||
|
||||
private static <T> T transaction(Path root, boolean write, int busyMillis, Operation<T> operation) {
|
||||
Objects.requireNonNull(operation);
|
||||
if (busyMillis < 0 || busyMillis > 30000) throw ProtocolException.invalid("SQLite busy timeout must be 0–30000 ms");
|
||||
Path path = checked(root);
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.missing("Missing AIE database: " + path);
|
||||
var active = SESSIONS.get();
|
||||
var nested = active.get(path);
|
||||
if (nested != null) {
|
||||
if (write && !nested.write) {
|
||||
nested.rollbackOnly = true;
|
||||
throw ProtocolException.invalid("Cannot start a write inside a read transaction");
|
||||
}
|
||||
try { return operation.run(nested.connection); }
|
||||
catch (SQLException failure) { nested.rollbackOnly = true; throw problem(failure, busyMillis); }
|
||||
catch (RuntimeException | Error failure) { nested.rollbackOnly = true; throw failure; }
|
||||
}
|
||||
var committed = new ArrayList<Runnable>();
|
||||
var rolledBack = new ArrayList<Runnable>();
|
||||
T result;
|
||||
try (var connection = connect(path, write, busyMillis)) {
|
||||
validate(connection);
|
||||
connection.setAutoCommit(false);
|
||||
var session = new Session(connection, write);
|
||||
active.put(path, session);
|
||||
try {
|
||||
result = operation.run(connection);
|
||||
if (session.rollbackOnly) {
|
||||
connection.rollback();
|
||||
if (write) throw ProtocolException.validation("SQLite transaction rolled back after a nested operation failed");
|
||||
} else { connection.commit(); committed.addAll(session.committed); }
|
||||
} catch (SQLException | RuntimeException | Error failure) {
|
||||
rollback(connection, failure);
|
||||
rolledBack.addAll(session.rolledBack.reversed());
|
||||
throw failure;
|
||||
} finally { active.remove(path); }
|
||||
} catch (SQLException failure) {
|
||||
var translated = problem(failure, busyMillis); recover(rolledBack, translated); throw translated;
|
||||
} catch (RuntimeException | Error failure) { recover(rolledBack, failure); throw failure; }
|
||||
finally { if (active.isEmpty()) SESSIONS.remove(); }
|
||||
for (var operationAfterCommit : committed) {
|
||||
try { operationAfterCommit.run(); }
|
||||
catch (RuntimeException failure) { throw new ProtocolException(1, "SQLite change committed; file cleanup needs recovery: " + failure.getMessage()); }
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static void recover(List<Runnable> operations, Throwable failure) {
|
||||
for (var operation : operations) {
|
||||
try { operation.run(); } catch (RuntimeException secondary) { failure.addSuppressed(secondary); }
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection connect(Path path, boolean write, int busyMillis) throws SQLException {
|
||||
var properties = new Properties();
|
||||
// READONLY / READWRITE, plus SQLITE_OPEN_URI. CREATE is deliberately absent.
|
||||
properties.setProperty("open_mode", Integer.toString((write ? 2 : 1) | 64));
|
||||
properties.setProperty("foreign_keys", "true");
|
||||
properties.setProperty("busy_timeout", Integer.toString(busyMillis));
|
||||
properties.setProperty("transaction_mode", write ? "IMMEDIATE" : "DEFERRED");
|
||||
return new JDBC().connect("jdbc:sqlite:" + path.toUri().toASCIIString(), properties);
|
||||
}
|
||||
|
||||
private static void validate(Connection connection) throws SQLException {
|
||||
try (var statement = connection.createStatement()) {
|
||||
try (var row = statement.executeQuery("PRAGMA application_id")) {
|
||||
if (!row.next() || row.getInt(1) != APPLICATION_ID)
|
||||
throw ProtocolException.validation("Not a recognized AIE SQLite database; use explicit initialization or migration");
|
||||
}
|
||||
try (var row = statement.executeQuery("PRAGMA user_version")) {
|
||||
if (!row.next() || row.getInt(1) != SCHEMA_VERSION)
|
||||
throw ProtocolException.validation("Unsupported AIE SQLite schema; use a compatible CLI and inspect compatibility");
|
||||
}
|
||||
try (var row = statement.executeQuery("SELECT schema_version FROM aie_schema WHERE singleton=1")) {
|
||||
if (!row.next() || row.getInt(1) != SCHEMA_VERSION)
|
||||
throw ProtocolException.validation("Inconsistent AIE SQLite schema metadata");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void rollback(Connection connection, Throwable failure) {
|
||||
try { if (!connection.getAutoCommit()) connection.rollback(); }
|
||||
catch (SQLException rollbackFailure) { failure.addSuppressed(rollbackFailure); }
|
||||
}
|
||||
|
||||
private static ProtocolException problem(SQLException failure, int busyMillis) {
|
||||
int code = failure.getErrorCode() & 0xff;
|
||||
if (code == 5 || code == 6)
|
||||
return ProtocolException.validation("AIE database is busy after a wait limited to " + busyMillis + " ms; retry after the other operation finishes");
|
||||
if (code == 19) return ProtocolException.validation("SQLite integrity constraint rejected the operation: " + failure.getMessage());
|
||||
return new ProtocolException(1, "SQLite operation failed: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package net.intrepid.aiengineering.filesystem;
|
||||
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
/** Typed record columns and ordered child rows. Never stores a serialized file or whole aggregate. */
|
||||
public final class SqliteRecords {
|
||||
private SqliteRecords() {}
|
||||
private static final Set<String> KINDS = Set.of("work", "discussion", "topic", "survey", "disposition", "decision", "plan", "epic", "run", "artifact", "gate", "receipt");
|
||||
private static String table(String kind) {
|
||||
if (!KINDS.contains(kind)) throw ProtocolException.invalid("Unknown record kind: " + kind);
|
||||
return "data_" + kind;
|
||||
}
|
||||
private static String field(RecordComponent component) {
|
||||
String name = component.getName();
|
||||
if (!name.matches("[a-zA-Z][a-zA-Z0-9]*")) throw ProtocolException.validation("Unsupported record field");
|
||||
return "f_" + name;
|
||||
}
|
||||
private static boolean list(RecordComponent component) { return component.getType() == List.class; }
|
||||
private static boolean number(RecordComponent component) {
|
||||
return Set.of(int.class, long.class, Integer.class, Long.class, boolean.class, Boolean.class).contains(component.getType());
|
||||
}
|
||||
private static boolean bool(RecordComponent component) { return component.getType() == boolean.class || component.getType() == Boolean.class; }
|
||||
private static boolean text(RecordComponent component) { return component.getType() == String.class || component.getType().isEnum(); }
|
||||
private static void key(PreparedStatement statement, String work, String id, int revision) throws SQLException {
|
||||
statement.setString(1, work); statement.setString(2, id); statement.setInt(3, revision);
|
||||
}
|
||||
private static void identity(PreparedStatement statement, String work, String kind, String id, int revision) throws SQLException {
|
||||
statement.setString(1, work); statement.setString(2, kind); statement.setString(3, id); statement.setInt(4, revision);
|
||||
}
|
||||
|
||||
private static void schema(Connection connection, String kind, Class<?> type) throws SQLException {
|
||||
if (!type.isRecord()) throw ProtocolException.invalid("Storage requires a domain record");
|
||||
String name = table(kind);
|
||||
var columns = new ArrayList<String>();
|
||||
for (var component : type.getRecordComponents()) {
|
||||
if (list(component)) columns.add(field(component) + "__present INTEGER NOT NULL DEFAULT 1 CHECK(" + field(component) + "__present IN (0,1))");
|
||||
else columns.add(field(component) + " " + (number(component) ? "INTEGER" : "TEXT")
|
||||
+ (!text(component) && !number(component) ? " CHECK(" + field(component) + " IS NULL OR json_valid(" + field(component) + "))" : ""));
|
||||
}
|
||||
try (var statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS " + name + " (work_id TEXT NOT NULL, local_id TEXT NOT NULL, storage_revision INTEGER NOT NULL, kind TEXT NOT NULL DEFAULT '" + kind
|
||||
+ "' CHECK(kind='" + kind + "')," + String.join(",", columns)
|
||||
+ ", PRIMARY KEY(work_id,local_id,storage_revision), FOREIGN KEY(work_id,kind,local_id,storage_revision) REFERENCES record_identity(work_id,kind,local_id,revision) DEFERRABLE INITIALLY DEFERRED)");
|
||||
for (var component : type.getRecordComponents()) if (list(component))
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS " + name + "_" + field(component)
|
||||
+ " (work_id TEXT NOT NULL,local_id TEXT NOT NULL,storage_revision INTEGER NOT NULL,ordinal INTEGER NOT NULL CHECK(ordinal>=0),value_kind TEXT NOT NULL CHECK(value_kind IN ('string','record')),value TEXT NOT NULL,"
|
||||
+ "CHECK(value_kind='string' OR json_valid(value)),PRIMARY KEY(work_id,local_id,storage_revision,ordinal),"
|
||||
+ "FOREIGN KEY(work_id,local_id,storage_revision) REFERENCES " + name + "(work_id,local_id,storage_revision) DEFERRABLE INITIALLY DEFERRED)");
|
||||
for (String property : List.of("title", "status")) if (Arrays.stream(type.getRecordComponents()).anyMatch(c -> c.getName().equals(property)))
|
||||
statement.execute("CREATE INDEX IF NOT EXISTS " + name + "_by_" + property + " ON " + name + "(f_" + property + ",work_id,local_id)");
|
||||
}
|
||||
}
|
||||
|
||||
public static int current(Path root, String work, String kind, String id) {
|
||||
table(kind);
|
||||
return SqliteDatabase.read(root, connection -> current(connection, work, kind, id));
|
||||
}
|
||||
private static int current(Connection connection, String work, String kind, String id) throws SQLException {
|
||||
try (var statement = connection.prepareStatement("SELECT revision FROM current_record WHERE work_id=? AND kind=? AND local_id=?")) {
|
||||
statement.setString(1, work); statement.setString(2, kind); statement.setString(3, id);
|
||||
try (var rows = statement.executeQuery()) { return rows.next() ? rows.getInt(1) : 0; }
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> ids(Path root, String kind, String work) {
|
||||
table(kind);
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
var ids = new ArrayList<String>();
|
||||
try (var statement = connection.prepareStatement("SELECT local_id FROM current_record WHERE kind=?" + (work == null ? "" : " AND work_id=?") + " ORDER BY local_id")) {
|
||||
statement.setString(1, kind); if (work != null) statement.setString(2, work);
|
||||
try (var rows = statement.executeQuery()) { while (rows.next()) ids.add(rows.getString(1)); }
|
||||
}
|
||||
return List.copyOf(ids);
|
||||
});
|
||||
}
|
||||
|
||||
public static <T> T get(Path root, String work, String kind, String id, int requestedRevision, Class<T> type) {
|
||||
String name = table(kind);
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
int revision = requestedRevision == 0 ? current(connection, work, kind, id) : requestedRevision;
|
||||
if (revision == 0) throw ProtocolException.missing("Record not found: " + kind + "/" + id);
|
||||
ObjectNode data = Documents.jsonTree(Map.of());
|
||||
try (var statement = connection.prepareStatement("SELECT * FROM " + name + " WHERE work_id=? AND local_id=? AND storage_revision=?")) {
|
||||
key(statement, work, id, revision);
|
||||
try (var rows = statement.executeQuery()) {
|
||||
if (!rows.next()) throw ProtocolException.missing("Record revision not found: " + kind + "/" + id + "/" + revision);
|
||||
for (var component : type.getRecordComponents()) {
|
||||
String column = field(component), property = component.getName();
|
||||
if (list(component)) {
|
||||
if (rows.getInt(column + "__present") == 0) data.putNull(property);
|
||||
else data.putArray(property);
|
||||
continue;
|
||||
}
|
||||
Object value = rows.getObject(column);
|
||||
if (value == null) { data.putNull(property); continue; }
|
||||
if (bool(component)) data.put(property, rows.getInt(column) != 0);
|
||||
else if (number(component)) data.put(property, rows.getLong(column));
|
||||
else if (text(component)) data.put(property, rows.getString(column));
|
||||
else data.set(property, Documents.parseJson(rows.getString(column), JsonNode.class));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var component : type.getRecordComponents()) if (list(component)) {
|
||||
if (data.get(component.getName()).isNull()) continue;
|
||||
var array = data.putArray(component.getName());
|
||||
try (var statement = connection.prepareStatement("SELECT value_kind,value FROM " + name + "_" + field(component) + " WHERE work_id=? AND local_id=? AND storage_revision=? ORDER BY ordinal")) {
|
||||
key(statement, work, id, revision);
|
||||
try (var rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
if (rows.getString(1).equals("string")) array.add(rows.getString(2));
|
||||
else array.add(Documents.parseJson(rows.getString(2), JsonNode.class));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Documents.jsonValue(data, type);
|
||||
});
|
||||
}
|
||||
|
||||
public static <T> void put(Path root, String work, String kind, String id, T value, Class<T> type, boolean replace, int documentVersion) {
|
||||
String name = table(kind);
|
||||
var data = Documents.jsonTree(value);
|
||||
String objectId = data.has("id") ? data.get("id").stringValue() : data.get("workId").stringValue();
|
||||
String owner = kind.equals("work") ? objectId : data.get("workId").stringValue();
|
||||
if (!id.equals(objectId) || !work.equals(owner)) throw ProtocolException.validation("Stored record identity/ownership mismatch: " + id);
|
||||
int revision = data.hasNonNull("revision") ? data.get("revision").intValue() : 1;
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
int old = current(connection, work, kind, id);
|
||||
if (!replace && old != 0) throw ProtocolException.invalid("Record already exists: " + id);
|
||||
if (replace && old == 0) throw ProtocolException.missing("Record not found: " + id);
|
||||
schema(connection, kind, type);
|
||||
try (var statement = connection.prepareStatement("INSERT INTO record_identity VALUES (?,?,?,?) ON CONFLICT DO NOTHING")) {
|
||||
identity(statement, work, kind, id, revision); statement.executeUpdate();
|
||||
}
|
||||
var components = Arrays.stream(type.getRecordComponents()).filter(c -> !list(c)).toList();
|
||||
String fields = String.join(",", components.stream().map(SqliteRecords::field).toList());
|
||||
String placeholders = String.join(",", Collections.nCopies(3 + components.size(), "?"));
|
||||
String updates = String.join(",", components.stream().map(c -> field(c) + "=excluded." + field(c)).toList());
|
||||
try (var statement = connection.prepareStatement("INSERT INTO " + name + "(work_id,local_id,storage_revision," + fields + ") VALUES (" + placeholders + ") ON CONFLICT(work_id,local_id,storage_revision) DO UPDATE SET " + updates)) {
|
||||
key(statement, work, id, revision); int position = 4;
|
||||
for (var component : components) {
|
||||
var node = data.get(component.getName());
|
||||
if (node == null || node.isNull()) statement.setNull(position, number(component) ? Types.INTEGER : Types.VARCHAR);
|
||||
else if (bool(component)) statement.setInt(position, node.booleanValue() ? 1 : 0);
|
||||
else if (number(component)) statement.setLong(position, node.longValue());
|
||||
else if (text(component)) statement.setString(position, node.stringValue());
|
||||
else statement.setString(position, Documents.json(node));
|
||||
position++;
|
||||
}
|
||||
statement.executeUpdate();
|
||||
}
|
||||
for (var component : type.getRecordComponents()) if (list(component)) {
|
||||
String child = name + "_" + field(component);
|
||||
boolean present;
|
||||
try { present = component.getAccessor().invoke(value) != null; }
|
||||
catch (ReflectiveOperationException failure) { throw ProtocolException.validation("Cannot inspect typed list presence: " + component.getName()); }
|
||||
try (var statement = connection.prepareStatement("UPDATE " + name + " SET " + field(component) + "__present=? WHERE work_id=? AND local_id=? AND storage_revision=?")) {
|
||||
statement.setInt(1, present ? 1 : 0); statement.setString(2, work); statement.setString(3, id); statement.setInt(4, revision); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("DELETE FROM " + child + " WHERE work_id=? AND local_id=? AND storage_revision=?")) {
|
||||
key(statement, work, id, revision); statement.executeUpdate();
|
||||
}
|
||||
var array = data.get(component.getName());
|
||||
if (array != null && !array.isNull()) try (var statement = connection.prepareStatement("INSERT INTO " + child + " VALUES (?,?,?,?,?,?)")) {
|
||||
int ordinal = 0;
|
||||
for (var node : array) {
|
||||
key(statement, work, id, revision); statement.setInt(4, ordinal++);
|
||||
statement.setString(5, node.isString() ? "string" : "record");
|
||||
statement.setString(6, node.isString() ? node.stringValue() : Documents.json(node)); statement.addBatch();
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO current_record VALUES (?,?,?,?) ON CONFLICT(work_id,kind,local_id) DO UPDATE SET revision=excluded.revision")) {
|
||||
identity(statement, work, kind, id, revision); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO record_format(work_id,kind,local_id,revision,document_version) VALUES (?,?,?,?,?) ON CONFLICT(work_id,kind,local_id,revision) DO UPDATE SET document_version=excluded.document_version,original_path=NULL,original_sha256=NULL")) {
|
||||
identity(statement, work, kind, id, revision); statement.setInt(5, documentVersion); statement.executeUpdate();
|
||||
}
|
||||
if (kind.equals("work")) {
|
||||
try (var statement = connection.prepareStatement("DELETE FROM record_reference WHERE work_id=? AND kind='work' AND local_id=? AND revision=?")) {
|
||||
key(statement, work, id, revision); statement.executeUpdate();
|
||||
}
|
||||
var owned = Map.of("discussions", "discussion", "topics", "topic", "surveys", "survey",
|
||||
"dispositions", "disposition", "decisions", "decision", "plans", "plan", "agentRuns", "run", "artifacts", "artifact");
|
||||
for (var entry : owned.entrySet()) {
|
||||
var references = data.get(entry.getKey());
|
||||
if (references == null || references.isNull()) continue;
|
||||
int ordinal = 0;
|
||||
for (var reference : references) {
|
||||
String target = reference.stringValue(); int targetRevision = current(connection, work, entry.getValue(), target);
|
||||
if (targetRevision == 0) throw ProtocolException.validation("Missing owned record: " + target);
|
||||
try (var statement = connection.prepareStatement("INSERT INTO record_reference VALUES (?,?,?,?,?,?,?,?,?,?)")) {
|
||||
identity(statement, work, kind, id, revision); statement.setString(5, entry.getKey()); statement.setInt(6, ordinal++);
|
||||
statement.setString(7, work); statement.setString(8, entry.getValue()); statement.setString(9, target); statement.setInt(10, targetRevision);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (kind.equals("epic")) {
|
||||
try (var statement = connection.prepareStatement("DELETE FROM epic_link WHERE parent_work_id=?")) {
|
||||
statement.setString(1, work); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO epic_link VALUES (?,?,?)")) {
|
||||
for (var child : data.get("children")) {
|
||||
statement.setString(1, work); statement.setString(2, child.get("workId").stringValue());
|
||||
statement.setInt(3, child.get("important").booleanValue() ? 1 : 0); statement.addBatch();
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public static <T> String raw(Path root, String work, String kind, String id, int revision, Class<T> type, String bodyField) {
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
int selected = revision == 0 ? current(connection, work, kind, id) : revision;
|
||||
int version;
|
||||
try (var statement = connection.prepareStatement("SELECT document_version,original_path,original_sha256 FROM record_format WHERE work_id=? AND kind=? AND local_id=? AND revision=?")) {
|
||||
identity(statement, work, kind, id, selected);
|
||||
try (var row = statement.executeQuery()) {
|
||||
if (!row.next()) throw ProtocolException.missing("Record format not found: " + id);
|
||||
version = row.getInt(1);
|
||||
if (row.getString(2) != null) {
|
||||
String original = Filespace.read(Filespace.resolve(root, row.getString(2)));
|
||||
if (!Revisions.hash(original).equals(row.getString(3))) throw ProtocolException.validation("Historical source representation changed: " + id);
|
||||
var represented = Documents.parseMarkdownDocument(original, type, bodyField);
|
||||
if (!Objects.equals(represented, get(root, work, kind, id, selected, type)))
|
||||
throw ProtocolException.validation("Typed historical record differs from its source representation: " + id);
|
||||
return original;
|
||||
}
|
||||
}
|
||||
}
|
||||
T value = get(root, work, kind, id, selected, type);
|
||||
if (version == 2) return Documents.markdownDocument(value, bodyField);
|
||||
return "---\n" + Documents.yaml(value).replaceFirst("^---\\n", "") + "---\n";
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,8 @@ public final class DiscussionImportService {
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
int code = failure instanceof ProtocolException p ? p.exitCode() : 1;
|
||||
if (SqliteDatabase.active(root)) throw new ProtocolException(code, "DF import rolled back: " + failure.getMessage()
|
||||
+ ". No Works from this transaction committed; run preview again to resume.");
|
||||
throw new ProtocolException(code, "DF import failed: " + failure.getMessage() + "; published Works: " + published
|
||||
+ ". Run preview again to resume; unpublished staging may remain for inspection.");
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ public final class PlanService {
|
||||
private final WorkService works = new WorkService();
|
||||
private final DecisionService decisions = new DecisionService();
|
||||
private Path path(Path root, String work, String id) { Work.identifier(id, "PLN"); return Filespace.resolve(works.folder(root, work), "plans/" + id + ".md"); }
|
||||
private Plan read(Path path) { return Documents.readMarkdownDocument(path, Plan.class, "description"); }
|
||||
private Plan read(Path path) { return RecordStorage.read(path, Plan.class, "description"); }
|
||||
public List<Plan> list(Path root, String work) {
|
||||
return works.load(root, work).plans().stream().map(id -> {
|
||||
var plan = read(path(root, work, id)); identity(plan, work, id); chain(root, plan); return plan;
|
||||
@@ -29,7 +29,7 @@ public final class PlanService {
|
||||
private List<Plan> chain(Path root, Plan current) {
|
||||
var history = new ArrayList<Plan>(); history.add(current); var next = current;
|
||||
for (int revision = current.revision() - 1; revision >= 1; revision--) {
|
||||
Path path = Revisions.history(works.folder(root, current.workId()), "plans", current.id(), revision); String original = Filespace.read(path);
|
||||
Path path = Revisions.history(works.folder(root, current.workId()), "plans", current.id(), revision); String original = RecordStorage.raw(path, Plan.class, "description");
|
||||
Revisions.chain(next.revision(), next.previousHash(), revision + 1, original);
|
||||
var prior = read(path); identity(prior, current.workId(), current.id());
|
||||
if (prior.revision() != revision) throw ProtocolException.validation("Invalid plan history revision: " + path);
|
||||
@@ -68,6 +68,13 @@ public final class PlanService {
|
||||
throw ProtocolException.invalid("Resolve pending discussion questions and surveys before creating a Plan");
|
||||
var plan = new Plan(1, id, workId, title, description, refs, List.of(), Plan.Status.OPEN, author, now, 1, null, now, author, "Plan created");
|
||||
Path path = path(root, workId, id), folder = works.folder(root, workId), workPath = Filespace.resolve(folder, "work.md");
|
||||
if (SqliteDatabase.active(root)) {
|
||||
var promotions = decisions.preparePlanAcceptance(root, workId, refs, id, author);
|
||||
promotions.publish(folder);
|
||||
RecordStorage.write(path, plan, Plan.class, "description", false);
|
||||
works.addReference(root, workId, "plans", id);
|
||||
return plan;
|
||||
}
|
||||
if (Files.exists(path)) throw ProtocolException.invalid("Already exists: " + path);
|
||||
String originalWork = Filespace.read(workPath), document = Documents.markdownDocument(plan, "description");
|
||||
var promotions = decisions.preparePlanAcceptance(root, workId, refs, id, author);
|
||||
@@ -95,10 +102,10 @@ public final class PlanService {
|
||||
private Plan mutate(Path root, String work, String id, String by, String reason, Function<Plan, Plan> mutation) {
|
||||
return Filespace.locked(root, () -> {
|
||||
works.editable(root, work); ProtocolException.text(by, "plan actor"); ProtocolException.text(reason, "plan change reason");
|
||||
var old = get(root, work, id); String original = Filespace.read(path(root, work, id)); var candidate = mutation.apply(old);
|
||||
var old = get(root, work, id); String original = RecordStorage.raw(path(root, work, id), Plan.class, "description"); var candidate = mutation.apply(old);
|
||||
if (candidate.equals(old)) return old;
|
||||
var changed = candidate.snapshot(by, reason, Revisions.hash(original));
|
||||
Revisions.replace(works.folder(root, work), "plans", id, old.revision(), original, Documents.markdownDocument(changed, "description"));
|
||||
RecordStorage.replaceRevision(works.folder(root, work), "plans", id, old.revision(), original, Documents.markdownDocument(changed, "description"), Plan.class, "description");
|
||||
works.touched(root, work, changed.updatedAt()); return changed;
|
||||
});
|
||||
}
|
||||
@@ -185,7 +192,10 @@ public final class PlanService {
|
||||
accepted(root, work, old.decisions()); old.requireExperimentReady(stepId);
|
||||
}
|
||||
if (!works.load(root, work).artifacts().containsAll(evidence)) throw ProtocolException.invalid("Unknown step evidence");
|
||||
if (target == Plan.Status.COMPLETED) new ArtifactService().validate(root, work);
|
||||
if (target == Plan.Status.COMPLETED) {
|
||||
new ArtifactService().validate(root, work);
|
||||
new ArtifactService().requireAvailable(root, work, evidence);
|
||||
}
|
||||
var changed = new Plan.Step(stepId, previous.title(), previous.description(), previous.acceptanceCriteria(), previous.dependsOn(), target, reason, evidence, Instant.now().toString());
|
||||
var steps = old.steps().stream().map(step -> step.id().equals(stepId) ? changed : step).toList();
|
||||
var status = old.status() == Plan.Status.OPEN && (target == Plan.Status.ACTIVE || target == Plan.Status.COMPLETED) ? Plan.Status.ACTIVE : old.status();
|
||||
@@ -216,6 +226,7 @@ public final class PlanService {
|
||||
.orElseThrow(() -> ProtocolException.missing("Experiment not found: " + experimentId));
|
||||
if (!works.load(root, work).artifacts().containsAll(evidence)) throw ProtocolException.invalid("Unknown experiment evidence");
|
||||
new ArtifactService().validate(root, work);
|
||||
new ArtifactService().requireAvailable(root, work, evidence);
|
||||
if (concern != null && !old.decisions().contains(concern)) throw ProtocolException.invalid("Questioned DEC must belong to the Plan");
|
||||
var result = experiment.finish(outcome, observation, interpretation, nextAction, evidence, concern, by);
|
||||
return old.withExperiments(old.experiments().stream().map(e -> e.id().equals(experimentId) ? result : e).toList());
|
||||
|
||||
@@ -3,7 +3,9 @@ package net.intrepid.aiengineering.project;
|
||||
import net.intrepid.aiengineering.filesystem.ProtocolException;
|
||||
import java.util.*;
|
||||
|
||||
public record ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories, Agents agents) {
|
||||
public record ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories, Agents agents,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) String storage) {
|
||||
public ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories, Agents agents) { this(schemaVersion, project, repositories, agents, null); }
|
||||
public ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories) { this(schemaVersion, project, repositories, null); }
|
||||
public record Executor(String adapter, String profile, String model,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) Integer timeoutSeconds) {
|
||||
@@ -25,6 +27,7 @@ public record ProjectConfig(int schemaVersion, Identity project, List<Repository
|
||||
public ProjectConfig {
|
||||
ProtocolException.schema(schemaVersion);
|
||||
if (project == null || repositories == null) throw ProtocolException.validation("project and repositories are required");
|
||||
if (storage != null && !storage.equals("sqlite")) throw ProtocolException.validation("Unsupported project storage: " + storage);
|
||||
repositories = List.copyOf(repositories);
|
||||
if (repositories.stream().map(Repository::id).distinct().count() != repositories.size())
|
||||
throw ProtocolException.validation("Duplicate repository IDs");
|
||||
|
||||
@@ -26,6 +26,10 @@ public final class ProjectService {
|
||||
if (!Files.isRegularFile(file)) throw ProtocolException.missing("Missing project configuration: " + file);
|
||||
}
|
||||
public ProjectConfig initialize(Path root, String name) {
|
||||
return initializeSqlite(root, name);
|
||||
}
|
||||
/** Compatibility fixture/bootstrap entry. Public CLI initialization defaults to SQLite. */
|
||||
public ProjectConfig initializeLegacy(Path root, String name) {
|
||||
root = canonical(root);
|
||||
var identity = new ProjectConfig.Identity(slug(name), name);
|
||||
var config = new ProjectConfig(1, identity, List.of());
|
||||
@@ -41,6 +45,57 @@ public final class ProjectService {
|
||||
ProtocolGuide.install(root);
|
||||
return config;
|
||||
}
|
||||
public ProjectConfig initializeSqlite(Path root, String name) {
|
||||
return initializeSqlite(root, name, true);
|
||||
}
|
||||
public ProjectConfig initializeSqlite(Path root, String name, boolean ignoreState) {
|
||||
root = canonical(root); final Path projectRoot = root;
|
||||
Path target = Filespace.resolve(root, ".ai-engineering");
|
||||
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.invalid("Project already exists: " + target);
|
||||
ProtocolGuide.preflight(root);
|
||||
var entries = ProtocolGuide.entries(root);
|
||||
Path instructions = Filespace.resolve(root, "AGENTS.md"), ignore = Filespace.resolve(root, ".gitignore");
|
||||
if (Files.exists(ignore) && !Files.isRegularFile(ignore, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.invalid(".gitignore must be a regular file");
|
||||
String originalInstructions = Files.exists(instructions) ? Filespace.read(instructions) : null;
|
||||
String originalIgnore = Files.exists(ignore) ? Filespace.read(ignore) : null;
|
||||
String nextInstructions = entries.get("AGENTS.md");
|
||||
String nextIgnore = originalIgnore == null ? "" : originalIgnore;
|
||||
if (ignoreState && nextIgnore.lines().noneMatch(line -> line.equals("/.ai-engineering/")))
|
||||
nextIgnore += (nextIgnore.isEmpty() || nextIgnore.endsWith("\n") ? "" : "\n") + "/.ai-engineering/\n";
|
||||
Path staging = Filespace.resolve(root, ".aie-bootstrap-" + UUID.randomUUID()); Filespace.directory(staging);
|
||||
boolean published = false;
|
||||
try {
|
||||
var initial = initializeLegacy(staging, name);
|
||||
SqliteDatabase.initialize(staging);
|
||||
var config = new ProjectConfig(initial.schemaVersion(), initial.project(), initial.repositories(), initial.agents(), "sqlite");
|
||||
Filespace.write(staging.resolve(".ai-engineering/ai-engineering.yaml"), Documents.yaml(config), true);
|
||||
SqliteDatabase.checkpoint(staging);
|
||||
Filespace.write(instructions, nextInstructions, originalInstructions != null);
|
||||
if (ignoreState && !Objects.equals(nextIgnore, originalIgnore)) Filespace.write(ignore, nextIgnore, originalIgnore != null);
|
||||
Filespace.moveDirectory(staging.resolve(".ai-engineering"), target); published = true;
|
||||
return config;
|
||||
} catch (RuntimeException failure) {
|
||||
if (!published) {
|
||||
try {
|
||||
restoreBootstrap(instructions, originalInstructions, nextInstructions);
|
||||
if (ignoreState) restoreBootstrap(ignore, originalIgnore, nextIgnore);
|
||||
} catch (RuntimeException recovery) { failure.addSuppressed(recovery); }
|
||||
}
|
||||
throw failure;
|
||||
} finally {
|
||||
try (var paths = Filespace.io(() -> Files.walk(staging))) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
if (!path.equals(staging)) Filespace.resolve(projectRoot, projectRoot.relativize(path).toString());
|
||||
Filespace.io(() -> { Files.delete(path); return null; });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private void restoreBootstrap(Path path, String original, String intended) {
|
||||
if (!Files.exists(path) || !Filespace.read(path).equals(intended)) return;
|
||||
if (original == null) Filespace.io(() -> { Files.delete(path); return null; });
|
||||
else Filespace.write(path, original, true);
|
||||
}
|
||||
public static String slug(String text) {
|
||||
ProtocolException.text(text, "name");
|
||||
String result = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFD)
|
||||
@@ -58,7 +113,7 @@ public final class ProjectService {
|
||||
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, config.agents());
|
||||
var updated = new ProjectConfig(1, config.project(), repositories, config.agents(), config.storage());
|
||||
Filespace.write(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), Documents.yaml(updated), true);
|
||||
return updated;
|
||||
});
|
||||
@@ -70,7 +125,7 @@ public final class ProjectService {
|
||||
}
|
||||
public ProjectConfig configureAgents(Path root, ProjectConfig.Agents agents) {
|
||||
return Filespace.locked(root, () -> {
|
||||
var original = load(root); var changed = new ProjectConfig(1, original.project(), original.repositories(), agents);
|
||||
var original = load(root); var changed = new ProjectConfig(1, original.project(), original.repositories(), agents, original.storage());
|
||||
if (!changed.equals(original)) Filespace.write(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), Documents.yaml(changed), true);
|
||||
return changed;
|
||||
});
|
||||
|
||||
@@ -7,8 +7,8 @@ import java.util.List;
|
||||
public final class ProtocolContract {
|
||||
private ProtocolContract() {}
|
||||
public static final String CLI_VERSION = "0.1.0";
|
||||
public static final int CURRENT = 3;
|
||||
public static final List<Integer> READABLE = List.of(1, 2, 3);
|
||||
public static final int CURRENT = 4;
|
||||
public static final List<Integer> READABLE = List.of(1, 2, 3, 4);
|
||||
/** Pre-versioned manifests describe the supported baseline contract, without rewriting them. */
|
||||
public static int effective(Integer declared) { return declared == null ? 1 : declared; }
|
||||
public static void require(Integer declared) {
|
||||
|
||||
@@ -13,8 +13,9 @@ public final class ProtocolGuide {
|
||||
+ "This project uses AI Engineering. Read `.ai-engineering/README.md` and\n"
|
||||
+ "`.ai-engineering/protocol.json` before engineering work. Run `aie status` and\n"
|
||||
+ "`aie next-actions`, then load the selected Work with `aie work context <WRK>`.\n"
|
||||
+ "Use `ai-engineering` if the `aie` alias is unavailable; without a CLI, read the\n"
|
||||
+ "portable files directly. Preserve the project rules outside this block.\n"
|
||||
+ "Use `ai-engineering` if the `aie` alias is unavailable. SQLite memory requires\n"
|
||||
+ "a compatible CLI; without one, read bootstrap guidance and report the tool gap.\n"
|
||||
+ "Never treat unreadable memory as an empty project. Preserve rules outside this block.\n"
|
||||
+ "Ask for missing Work discussion mode; only the human changes it or ends exploration.\n"
|
||||
+ "Never infer human approval; record it explicitly before significant commitments.\n" + END;
|
||||
private ProtocolGuide() {}
|
||||
@@ -52,6 +53,8 @@ public final class ProtocolGuide {
|
||||
throw ProtocolException.validation("Unsupported protocol discovery manifest");
|
||||
if (ProtocolContract.effective(protocolVersion) >= 3 && !capabilities.containsAll(List.of("work-guidance", "human-decision-request", "plan-experiments")))
|
||||
throw ProtocolException.validation("Contract 3 requires Work guidance, human decision requests and Plan experiments");
|
||||
if (ProtocolContract.effective(protocolVersion) >= 4 && !capabilities.containsAll(List.of("sqlite-storage", "local-memory", "quality-gates", "temporary-artifacts")))
|
||||
throw ProtocolException.validation("Contract 4 requires SQLite storage, local memory, quality gates and temporary artifacts");
|
||||
for (String value : List.of(entrypoint, instructions, configuration, works)) ProtocolException.text(value, "manifest path");
|
||||
aliases = List.copyOf(aliases); startup = List.copyOf(startup); capabilities = List.copyOf(capabilities);
|
||||
if (startup.isEmpty() || capabilities.isEmpty()) throw ProtocolException.validation("Incomplete protocol discovery manifest");
|
||||
@@ -101,13 +104,17 @@ public final class ProtocolGuide {
|
||||
if (start >= 0) return original.substring(0, start) + POINTER + original.substring(end + END.length());
|
||||
return original + (original.isEmpty() ? "" : original.endsWith("\n") ? "\n" : "\n\n") + POINTER + "\n";
|
||||
}
|
||||
public static Map<String, String> entries(Path root) {
|
||||
var content = new LinkedHashMap<String, String>();
|
||||
for (String name : List.of("README.md", "AGENTS.md", "protocol.json")) content.put(".ai-engineering/" + name, bundled(name));
|
||||
content.put("AGENTS.md", rootInstructions(root));
|
||||
return Collections.unmodifiableMap(content);
|
||||
}
|
||||
public static Report install(Path root) {
|
||||
requireSupportedVersion(root);
|
||||
return Filespace.locked(root, () -> {
|
||||
requireSupportedVersion(root);
|
||||
var content = new LinkedHashMap<String, String>();
|
||||
for (String name : List.of("README.md", "AGENTS.md", "protocol.json")) content.put(".ai-engineering/" + name, bundled(name));
|
||||
content.put("AGENTS.md", rootInstructions(root));
|
||||
var content = entries(root);
|
||||
var originals = new LinkedHashMap<String, String>();
|
||||
for (var item : content.entrySet()) {
|
||||
Path path = Filespace.resolve(root, item.getKey());
|
||||
|
||||
@@ -49,6 +49,12 @@ public final class CompatibilityService {
|
||||
try { ProtocolGuide.validate(root); }
|
||||
catch (RuntimeException e) { invalid(findings, ".ai-engineering/protocol.json", "entry-contract", e.getMessage()); }
|
||||
}
|
||||
try { if (SqliteDatabase.active(root)) return inspectSqlite(root, findings); }
|
||||
catch (RuntimeException failure) {
|
||||
findings.add(new Finding(".ai-engineering/aie.db", "sqlite", failure.getMessage() != null && failure.getMessage().contains("Unsupported") ? State.UNSUPPORTED : State.INVALID,
|
||||
Map.of(), List.of(), failure.getMessage() == null ? "Invalid SQLite storage" : failure.getMessage()));
|
||||
return report(findings, true);
|
||||
}
|
||||
Path workspace = Filespace.resolve(root, ".ai-engineering/works");
|
||||
Path sequence = Filespace.resolve(root, ".ai-engineering/works/.sequence.yaml");
|
||||
if (Files.exists(sequence)) inspect(root, root.relativize(sequence).toString(), "sequence", WorkService.Sequence.class, null, false, findings);
|
||||
@@ -95,11 +101,44 @@ public final class CompatibilityService {
|
||||
}
|
||||
} catch (RuntimeException ignored) { /* The Work's parse diagnostic was already recorded above. */ }
|
||||
});
|
||||
// Presence/version inspection is independent from structural/evidence validation.
|
||||
return report(findings, false);
|
||||
}
|
||||
private Report inspectSqlite(Path root, List<Finding> findings) {
|
||||
SqliteDatabase.read(root, connection -> {
|
||||
findings.add(new Finding(".ai-engineering/aie.db", "sqlite", State.CURRENT,
|
||||
Map.of("schemaVersion", Integer.toString(SqliteDatabase.SCHEMA_VERSION)), List.of(), "Explicit SQLite backend; no file conversion on read."));
|
||||
try (var statement = connection.createStatement(); var rows = statement.executeQuery("SELECT work_id,kind,local_id,revision FROM record_identity ORDER BY work_id,kind,local_id,revision")) {
|
||||
while (rows.next()) {
|
||||
String work = rows.getString(1), kind = rows.getString(2), id = rows.getString(3); int revision = rows.getInt(4);
|
||||
String path = ".ai-engineering/aie.db#" + work + "/" + kind + "/" + id + "/r" + revision;
|
||||
try {
|
||||
Class<?> type = switch (kind) {
|
||||
case "work" -> Work.class; case "discussion" -> DiscussionEntry.class; case "decision" -> Decision.class;
|
||||
case "plan" -> Plan.class; case "topic" -> Topic.class; case "survey" -> Survey.class; case "disposition" -> Disposition.class;
|
||||
case "epic" -> Epic.class; case "run" -> AgentRun.class; case "artifact" -> Artifact.class;
|
||||
case "gate" -> QualityGates.Result.class; case "receipt" -> net.intrepid.aiengineering.artifact.ProtocolReceipt.class;
|
||||
default -> throw ProtocolException.validation("Unknown SQLite record kind: " + kind);
|
||||
};
|
||||
SqliteRecords.get(root, work, kind, id, revision, type);
|
||||
if (SqliteRecords.current(root, work, kind, id) == 0) throw ProtocolException.validation("Missing current record pointer");
|
||||
findings.add(new Finding(path, kind, State.CURRENT, Map.of("schemaVersion", "1"), List.of(), "Readable typed SQLite record."));
|
||||
} catch (RuntimeException failure) {
|
||||
findings.add(new Finding(path, kind, failure.getMessage() != null && failure.getMessage().contains("Unsupported") ? State.UNSUPPORTED : State.INVALID,
|
||||
Map.of(), List.of(), failure.getMessage() == null ? "Invalid SQLite record" : failure.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return report(findings, true);
|
||||
}
|
||||
private Report report(List<Finding> findings, boolean sqlite) {
|
||||
// Presence/version inspection is independent from completion readiness.
|
||||
State state = findings.stream().map(Finding::state).max(Comparator.naturalOrder()).orElse(State.CURRENT);
|
||||
boolean readable = state == State.CURRENT || state == State.LEGACY_COMPATIBLE;
|
||||
var guidance = new ArrayList<String>();
|
||||
if (readable) guidance.add("No migration is required. Keep readable historical and COMPLETED Works in their existing formats.");
|
||||
if (readable) guidance.add(sqlite ? "SQLite is selected explicitly. Use the CLI for engineering memory; reads do not migrate data."
|
||||
: "No migration is required for legacy reading. Keep readable historical and COMPLETED Works in their existing formats.");
|
||||
else guidance.add("Unsupported versions require a compatible CLI; invalid files require deliberate repair. No migration route is inferred.");
|
||||
guidance.add("onboard refreshes entry instructions only, with backups; it does not convert Works or their history.");
|
||||
guidance.add("Compatibility describes storage readability, not completion readiness or evidence integrity. Run aie project validate separately.");
|
||||
|
||||
@@ -96,7 +96,7 @@ public final class EpicCoordinator {
|
||||
if (ids.size() != 1) throw ProtocolException.validation("System EPIC completion requires one owned aggregate receipt");
|
||||
var artifact = artifacts.list(root, work.id()).stream().filter(a -> a.id().equals(ids.getFirst())).findFirst()
|
||||
.orElseThrow(() -> ProtocolException.validation("Missing EPIC receipt artifact"));
|
||||
var receipt = Documents.readJson(Filespace.resolve(works.folder(root, work.id()), artifact.path()), Receipt.class);
|
||||
var receipt = artifacts.readReceipt(root, work.id(), artifact, Receipt.class);
|
||||
if (!receipt.workId().equals(work.id()) || !receipt.policyHash().equals(delegation.policyHash())
|
||||
|| !artifact.author().equals("system:epic") || !artifact.origin().equals(RECEIPT_ORIGIN + Revisions.hash(Documents.json(receipt))))
|
||||
throw ProtocolException.validation("Invalid EPIC receipt provenance");
|
||||
@@ -123,18 +123,18 @@ public final class EpicCoordinator {
|
||||
var existing = artifacts.list(root, definition.workId()).stream().filter(a -> a.origin().equals(origin)).toList();
|
||||
if (existing.size() > 1) throw ProtocolException.validation("Duplicate EPIC receipts for the same inputs");
|
||||
Artifact evidence;
|
||||
if (existing.isEmpty()) evidence = artifacts.attachBytes(root, definition.workId(), json.getBytes(java.nio.charset.StandardCharsets.UTF_8),
|
||||
if (existing.isEmpty()) evidence = artifacts.attachReceipt(root, definition.workId(), receipt,
|
||||
"Deterministic EPIC aggregate receipt under explicitly authorized policy", origin, "system:epic");
|
||||
else {
|
||||
evidence = existing.getFirst(); artifacts.validate(root, definition.workId());
|
||||
if (!Filespace.read(Filespace.resolve(works.folder(root, definition.workId()), evidence.path())).equals(json)) throw ProtocolException.validation("Conflicting EPIC receipt content");
|
||||
if (!Documents.json(artifacts.readReceipt(root, definition.workId(), evidence, Receipt.class)).equals(json)) throw ProtocolException.validation("Conflicting EPIC receipt content");
|
||||
}
|
||||
var current = works.load(root, definition.workId()); var criteria = new ArrayList<Work.CriterionResult>();
|
||||
for (int i = 0; i < current.acceptanceCriteria().size(); i++) criteria.add(new Work.CriterionResult(i + 1, current.acceptanceCriteria().get(i), List.of(evidence.id())));
|
||||
var completion = new Work.Completion(Instant.now().toString(), "system:epic", "Authorized aggregate condition satisfied; requester=" + requester,
|
||||
false, verification.scopeHash(root, current), criteria, List.of(), "Coordination-only delivery; canonical integration is evidenced by the child completions",
|
||||
Work.CompletionOrigin.SYSTEM_EPIC, new Work.Delegation(receipt.policyHash(), definition.authorization(), trigger, requester, requestId));
|
||||
return works.recordCompletion(root, current.id(), completion);
|
||||
return verification.recordCompletion(root, current.id(), completion);
|
||||
}
|
||||
private Set<String> selected(Map<String, Epic> definitions, String target) {
|
||||
if (target == null) return new HashSet<>(definitions.keySet());
|
||||
|
||||
@@ -69,7 +69,7 @@ public final class PlanCoordinator {
|
||||
var aggregation = completion.aggregation();
|
||||
var artifact = artifacts.list(root, work.id()).stream().filter(a -> a.id().equals(aggregation.receipt())).findFirst()
|
||||
.orElseThrow(() -> ProtocolException.validation("Missing Plan aggregate receipt"));
|
||||
var receipt = Documents.readJson(Filespace.resolve(works.folder(root, work.id()), artifact.path()), Receipt.class);
|
||||
var receipt = artifacts.readReceipt(root, work.id(), artifact, Receipt.class);
|
||||
if (!receipt.workId().equals(work.id()) || !receipt.inputHash().equals(aggregation.inputHash())
|
||||
|| !artifact.author().equals("system:plans") || !artifact.origin().equals(RECEIPT_ORIGIN + Revisions.hash(Documents.json(receipt))))
|
||||
throw ProtocolException.validation("Invalid Plan receipt provenance");
|
||||
@@ -108,15 +108,15 @@ public final class PlanCoordinator {
|
||||
var existing = artifacts.list(root, id).stream().filter(a -> a.origin().equals(origin)).toList();
|
||||
if (existing.size() > 1) throw ProtocolException.validation("Duplicate Plan receipts for the same inputs");
|
||||
Artifact artifact;
|
||||
if (existing.isEmpty()) artifact = artifacts.attachBytes(root, id, json.getBytes(java.nio.charset.StandardCharsets.UTF_8),
|
||||
if (existing.isEmpty()) artifact = artifacts.attachReceipt(root, id, receipt,
|
||||
"Deterministic aggregation of completed Plans and reviewed cancellations; not semantic verification of prose criteria", origin, "system:plans");
|
||||
else {
|
||||
artifact = existing.getFirst(); artifacts.validate(root, id);
|
||||
if (!Filespace.read(Filespace.resolve(works.folder(root, id), artifact.path())).equals(json)) throw ProtocolException.validation("Conflicting Plan receipt content");
|
||||
if (!Documents.json(artifacts.readReceipt(root, id, artifact, Receipt.class)).equals(json)) throw ProtocolException.validation("Conflicting Plan receipt content");
|
||||
}
|
||||
work = works.load(root, id); var criteria = new ArrayList<Work.CriterionResult>();
|
||||
for (int i = 0; i < work.acceptanceCriteria().size(); i++) criteria.add(new Work.CriterionResult(i + 1, work.acceptanceCriteria().get(i), List.of(artifact.id())));
|
||||
works.recordCompletion(root, id, new Work.Completion(Instant.now().toString(), "system:plans", "All required Plans completed; requester=" + requester,
|
||||
verification.recordCompletion(root, id, new Work.Completion(Instant.now().toString(), "system:plans", "All required Plans completed; requester=" + requester,
|
||||
false, verification.scopeHash(root, work), criteria, List.of(), "Canonical changes and execution results are recorded in the Plan step evidence",
|
||||
Work.CompletionOrigin.SYSTEM_PLANS, null, new Work.Aggregation(artifact.id(), receipt.inputHash(), requester, requestId)));
|
||||
}
|
||||
@@ -126,7 +126,11 @@ public final class PlanCoordinator {
|
||||
requireValid(root, id); new EpicService().definitions(root);
|
||||
T result = operation.get();
|
||||
try { return new Mutation<>(result, reconcile(root, id, requester, key)); }
|
||||
catch (RuntimeException failure) { throw persisted(id, failure); }
|
||||
catch (RuntimeException failure) {
|
||||
if (SqliteDatabase.active(root)) throw new ProtocolException(failure instanceof ProtocolException p ? p.exitCode() : 1,
|
||||
"Change rolled back for " + id + "; inspect coordination: " + failure.getMessage());
|
||||
throw persisted(id, failure);
|
||||
}
|
||||
});
|
||||
}
|
||||
public static ProtocolException persisted(String id, RuntimeException failure) {
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
package net.intrepid.aiengineering.verification;
|
||||
|
||||
import net.intrepid.aiengineering.artifact.ArtifactService;
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.project.ProjectConfig;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/** Records externally observed checks. Never executes a repository command or infers human approval. */
|
||||
public final class QualityGates {
|
||||
public record Definition(String scope, String id, String title, String procedure, List<String> inputs,
|
||||
boolean evidenceRequired, int revision, String updatedBy) {
|
||||
public Definition {
|
||||
if (!"project".equals(scope)) Work.identifier(scope, "WRK");
|
||||
ProjectConfig.identifier(id); ProtocolException.text(title, "gate title");
|
||||
ProtocolException.text(procedure, "gate procedure"); ProtocolException.text(updatedBy, "gate actor");
|
||||
inputs = List.copyOf(inputs);
|
||||
if (inputs.isEmpty() || new HashSet<>(inputs).size() != inputs.size() || revision < 1)
|
||||
throw ProtocolException.invalid("Gate requires unique input paths and a positive revision");
|
||||
inputs.forEach(path -> ProtocolException.text(path, "gate input"));
|
||||
}
|
||||
public String key() { return scope + "/" + id; }
|
||||
}
|
||||
public enum Outcome { PASS, FAIL }
|
||||
public record Result(int schemaVersion, String id, String workId, Definition definition, String evaluatedHash,
|
||||
String invocation, Outcome outcome, String summary, List<String> evidence, String by, String observedAt) {
|
||||
public Result {
|
||||
ProtocolException.schema(schemaVersion); Work.identifier(id, "GAT"); Work.identifier(workId, "WRK");
|
||||
Objects.requireNonNull(definition); Objects.requireNonNull(outcome);
|
||||
if (evaluatedHash == null || !evaluatedHash.matches("[a-f0-9]{64}")) throw ProtocolException.validation("Invalid evaluated gate hash");
|
||||
ProtocolException.text(invocation, "observed invocation"); ProtocolException.text(summary, "gate summary");
|
||||
if (summary.length() > 2000) throw ProtocolException.invalid("Gate summary exceeds 2000 characters; attach temporary detail instead");
|
||||
ProtocolException.text(by, "gate observer"); Instant.parse(observedAt); evidence = List.copyOf(evidence);
|
||||
}
|
||||
}
|
||||
public record View(Definition definition, String evaluatedHash, Result latest, boolean satisfied, String pending) {}
|
||||
private final WorkService works = new WorkService();
|
||||
private void sqlite(Path root) {
|
||||
if (!SqliteDatabase.active(root)) throw ProtocolException.validation("Quality gates require SQLite; use the explicit storage migration first");
|
||||
}
|
||||
public Definition configure(Path root, String scope, String id, String title, String procedure,
|
||||
List<String> inputs, boolean evidenceRequired, String by) {
|
||||
sqlite(root);
|
||||
var candidate = new Definition(scope, id, title, procedure, inputs, evidenceRequired, 1, by);
|
||||
for (String input : candidate.inputs()) input(root, input);
|
||||
return Filespace.locked(root, () -> {
|
||||
if (!scope.equals("project")) works.editable(root, scope);
|
||||
int revision = definitions(root, scope).stream().filter(d -> d.id().equals(id)).mapToInt(Definition::revision).max().orElse(0) + 1;
|
||||
var definition = new Definition(scope, id, title, procedure, inputs, evidenceRequired, revision, by);
|
||||
return SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("INSERT INTO quality_gate VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(scope,gate_id) DO UPDATE SET title=excluded.title,procedure=excluded.procedure,evidence_required=excluded.evidence_required,revision=excluded.revision,updated_by=excluded.updated_by")) {
|
||||
statement.setString(1, scope); statement.setString(2, id); statement.setString(3, scope.equals("project") ? null : scope);
|
||||
statement.setString(4, title); statement.setString(5, procedure); statement.setInt(6, evidenceRequired ? 1 : 0);
|
||||
statement.setInt(7, revision); statement.setString(8, by); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("DELETE FROM quality_gate_input WHERE scope=? AND gate_id=?")) {
|
||||
statement.setString(1, scope); statement.setString(2, id); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO quality_gate_input VALUES (?,?,?,?)")) {
|
||||
int ordinal = 0;
|
||||
for (String input : inputs) {
|
||||
statement.setString(1, scope); statement.setString(2, id); statement.setInt(3, ordinal++); statement.setString(4, input); statement.addBatch();
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
return definition;
|
||||
});
|
||||
});
|
||||
}
|
||||
private List<Definition> definitions(Path root, String scope) {
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
var result = new ArrayList<Definition>();
|
||||
try (var statement = connection.prepareStatement("SELECT gate_id,title,procedure,evidence_required,revision,updated_by FROM quality_gate WHERE scope=? ORDER BY gate_id")) {
|
||||
statement.setString(1, scope);
|
||||
try (var rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
var inputs = new ArrayList<String>();
|
||||
try (var child = connection.prepareStatement("SELECT path FROM quality_gate_input WHERE scope=? AND gate_id=? ORDER BY ordinal")) {
|
||||
child.setString(1, scope); child.setString(2, rows.getString(1));
|
||||
try (var values = child.executeQuery()) { while (values.next()) inputs.add(values.getString(1)); }
|
||||
}
|
||||
result.add(new Definition(scope, rows.getString(1), rows.getString(2), rows.getString(3), inputs, rows.getBoolean(4), rows.getInt(5), rows.getString(6)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(result);
|
||||
});
|
||||
}
|
||||
public List<Definition> definitions(Path root, String work, boolean includeProject) {
|
||||
if (!SqliteDatabase.active(root)) return List.of();
|
||||
works.load(root, work);
|
||||
var all = new ArrayList<Definition>();
|
||||
if (includeProject) all.addAll(definitions(root, "project"));
|
||||
all.addAll(definitions(root, work)); return List.copyOf(all);
|
||||
}
|
||||
private Path input(Path root, String relative) {
|
||||
Path path = Filespace.resolve(root, relative);
|
||||
if (path.startsWith(root.resolve(".ai-engineering")) || path.startsWith(root.resolve(".git")))
|
||||
throw ProtocolException.invalid("Gate inputs must be outside AIE state and Git internals: " + relative);
|
||||
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.validation("Missing gate input: " + relative);
|
||||
return path;
|
||||
}
|
||||
private boolean excluded(Path root, Path path) {
|
||||
Path relative = root.relativize(path);
|
||||
return relative.getNameCount() > 0 && Set.of(".ai-engineering", ".git").contains(relative.getName(0).toString());
|
||||
}
|
||||
public String fingerprint(Path root, String work, Definition definition) {
|
||||
var hashes = new TreeMap<String, String>();
|
||||
for (String relative : definition.inputs()) {
|
||||
Path selected = input(root, relative);
|
||||
try (var paths = Filespace.io(() -> Files.walk(selected))) {
|
||||
for (Path path : paths.filter(path -> !excluded(root, path)).sorted().toList()) {
|
||||
Filespace.resolve(root, root.relativize(path).toString());
|
||||
if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
hashes.put(root.relativize(path).toString(), "directory"); continue;
|
||||
}
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.validation("Unsupported gate input: " + path);
|
||||
hashes.put(root.relativize(path).toString(), Revisions.hash(Filespace.io(() -> Files.readAllBytes(path))));
|
||||
}
|
||||
} catch (java.io.UncheckedIOException failure) { throw new ProtocolException(1, "Cannot read gate inputs: " + failure.getMessage()); }
|
||||
}
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
var w = works.load(root, work); var data = new LinkedHashMap<String, Object>();
|
||||
data.put("definition", definition); data.put("files", hashes);
|
||||
data.put("scope", List.of(w.id(), w.title(), w.description(), w.goal(), w.motivation(), w.constraints(), w.acceptanceCriteria(), w.repositories()));
|
||||
data.put("guidance", w.guidance());
|
||||
var decisions = new ArrayList<String>();
|
||||
try (var statement = connection.prepareStatement("SELECT local_id,revision FROM current_record WHERE work_id=? AND kind='decision' ORDER BY local_id")) {
|
||||
statement.setString(1, work);
|
||||
try (var rows = statement.executeQuery()) { while (rows.next()) decisions.add(rows.getString(1) + ":" + rows.getInt(2)); }
|
||||
}
|
||||
data.put("decisions", decisions); return Revisions.hash(Documents.json(data));
|
||||
});
|
||||
}
|
||||
public List<Result> history(Path root, String work) {
|
||||
if (!SqliteDatabase.active(root)) return List.of();
|
||||
works.load(root, work);
|
||||
return SqliteDatabase.read(root, connection -> SqliteRecords.ids(root, "gate", work).stream()
|
||||
.map(id -> SqliteRecords.get(root, work, "gate", id, 0, Result.class))
|
||||
.sorted(Comparator.comparingLong(result -> Long.parseLong(result.id().substring(4)))).toList());
|
||||
}
|
||||
public List<View> inspect(Path root, String work) {
|
||||
if (!SqliteDatabase.active(root)) return List.of();
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
var history = history(root, work); var views = new ArrayList<View>();
|
||||
for (var definition : definitions(root, work, true)) {
|
||||
var latest = history.stream().filter(r -> r.definition().key().equals(definition.key())).reduce((a, b) -> b).orElse(null);
|
||||
String hash;
|
||||
try { hash = fingerprint(root, work, definition); }
|
||||
catch (ProtocolException problem) { views.add(new View(definition, null, latest, false, problem.getMessage())); continue; }
|
||||
boolean current = latest != null && latest.definition().equals(definition) && latest.evaluatedHash().equals(hash);
|
||||
boolean satisfied = current && latest.outcome() == Outcome.PASS;
|
||||
views.add(new View(definition, hash, latest, satisfied, satisfied ? "" : !current ? "Not evaluated for the current state" : "Latest evaluation failed"));
|
||||
}
|
||||
return List.copyOf(views);
|
||||
});
|
||||
}
|
||||
public List<String> pending(Path root, String work) {
|
||||
return inspect(root, work).stream().filter(view -> !view.satisfied()).map(view -> "Gate " + view.definition().key() + ": " + view.pending()).toList();
|
||||
}
|
||||
public Result record(Path root, String work, String gateKey, String expected, String invocation,
|
||||
Outcome outcome, String summary, List<String> evidence, String by, boolean observed) {
|
||||
sqlite(root);
|
||||
if (!observed) throw ProtocolException.invalid("--observed is required to attest an actual external evaluation");
|
||||
return Filespace.locked(root, () -> {
|
||||
var w = works.editable(root, work);
|
||||
var definition = definitions(root, work, true).stream().filter(d -> d.key().equals(gateKey)).findFirst()
|
||||
.orElseThrow(() -> ProtocolException.missing("Gate not configured: " + gateKey));
|
||||
String hash = fingerprint(root, work, definition);
|
||||
if (!hash.equals(expected)) throw ProtocolException.validation("Gate state changed or --expect differs; evaluate the current fingerprint");
|
||||
if (definition.evidenceRequired() && evidence.isEmpty()) throw ProtocolException.validation("Gate requires temporary evidence");
|
||||
if (!w.artifacts().containsAll(evidence)) throw ProtocolException.invalid("Unknown gate evidence");
|
||||
new ArtifactService().validate(root, work);
|
||||
new ArtifactService().requireAvailable(root, work, evidence);
|
||||
String id = works.nextReference(SqliteRecords.ids(root, "gate", work), "GAT");
|
||||
var result = new Result(1, id, work, definition, hash, invocation, outcome, summary, evidence, by, Instant.now().toString());
|
||||
if (!hash.equals(fingerprint(root, work, definition))) throw ProtocolException.validation("Gate inputs changed while recording the evaluation");
|
||||
SqliteRecords.put(root, work, "gate", id, result, Result.class, false, 1); return result;
|
||||
});
|
||||
}
|
||||
public void freeze(Path root, Work work, String completedAt) {
|
||||
if (!SqliteDatabase.active(root)) return;
|
||||
var views = inspect(root, work.id());
|
||||
var pending = views.stream().filter(v -> !v.satisfied()).map(v -> v.definition().key()).toList();
|
||||
if (!pending.isEmpty()) throw ProtocolException.validation("Required gates pending: " + pending);
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("INSERT INTO quality_delivery VALUES (?,?,?)")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, completedAt); statement.setInt(3, views.size()); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO quality_delivery_gate(work_id,completed_at,gate_key,result_id,result_sha256) VALUES (?,?,?,?,?)")) {
|
||||
for (var view : views) {
|
||||
statement.setString(1, work.id()); statement.setString(2, completedAt); statement.setString(3, view.definition().key());
|
||||
statement.setString(4, view.latest().id()); statement.setString(5, Revisions.hash(Documents.json(view.latest()))); statement.addBatch();
|
||||
}
|
||||
statement.executeBatch();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
public void validateHistory(Path root, Work work) {
|
||||
if (!SqliteDatabase.active(root)) return;
|
||||
SqliteDatabase.read(root, connection -> {
|
||||
for (var completion : work.completions()) {
|
||||
int count;
|
||||
try (var statement = connection.prepareStatement("SELECT gate_count FROM quality_delivery WHERE work_id=? AND completed_at=?")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, completion.at());
|
||||
try (var row = statement.executeQuery()) {
|
||||
if (!row.next()) throw ProtocolException.validation("Missing delivered gate snapshot: " + work.id());
|
||||
count = row.getInt(1);
|
||||
}
|
||||
}
|
||||
int found = 0;
|
||||
try (var statement = connection.prepareStatement("SELECT gate_key,result_id,result_sha256 FROM quality_delivery_gate WHERE work_id=? AND completed_at=?")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, completion.at());
|
||||
try (var rows = statement.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
var result = SqliteRecords.get(root, work.id(), "gate", rows.getString(2), 1, Result.class);
|
||||
if (result.outcome() != Outcome.PASS || !result.definition().key().equals(rows.getString(1))
|
||||
|| !Revisions.hash(Documents.json(result)).equals(rows.getString(3)))
|
||||
throw ProtocolException.validation("Invalid delivered gate result");
|
||||
found++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count != found) throw ProtocolException.validation("Incomplete delivered gate snapshot");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package net.intrepid.aiengineering.verification;
|
||||
|
||||
import net.intrepid.aiengineering.agent.AgentRun;
|
||||
import net.intrepid.aiengineering.artifact.Artifact;
|
||||
import net.intrepid.aiengineering.decision.Decision;
|
||||
import net.intrepid.aiengineering.discussion.*;
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import net.intrepid.aiengineering.planning.Plan;
|
||||
import net.intrepid.aiengineering.project.*;
|
||||
import net.intrepid.aiengineering.work.*;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Explicit one-project conversion. Originals and the active native installation are never edited. */
|
||||
public final class StorageMigration {
|
||||
private static final String JOURNAL = ".ai-engineering/.local/sqlite-migration/state.json";
|
||||
private static final String GUARD = ".ai-engineering/works/SQLITE-STORAGE";
|
||||
private static final String GUARD_TEXT = "SQLite is authoritative. Use a CLI supporting protocol contract 4. Legacy Work documents are retained originals, not writable state.\n";
|
||||
public record State(String operation, String phase, String fingerprint, Map<String, String> sourceHashes,
|
||||
Map<String, String> publishedHashes, String databaseHash) {
|
||||
public State {
|
||||
if (!operation.matches("[0-9a-f-]{36}")) throw ProtocolException.validation("Invalid migration operation");
|
||||
sourceHashes = Collections.unmodifiableMap(new TreeMap<>(sourceHashes));
|
||||
publishedHashes = Collections.unmodifiableMap(new TreeMap<>(publishedHashes));
|
||||
}
|
||||
State phase(String next) { return new State(operation, next, fingerprint, sourceHashes, publishedHashes, databaseHash); }
|
||||
}
|
||||
public record Report(int schemaVersion, boolean valid, String phase, String fingerprint, int works,
|
||||
String backup, List<String> issues, String nextAction) {
|
||||
public Report { issues = List.copyOf(issues); }
|
||||
}
|
||||
private final Consumer<String> boundary;
|
||||
public StorageMigration() { this(phase -> {}); }
|
||||
/** Package-local fault injection for disposable recovery fixtures. */
|
||||
StorageMigration(Consumer<String> boundary) { this.boundary = boundary; }
|
||||
private static String relative(Path root, Path path) { return root.relativize(path).toString().replace('\\', '/'); }
|
||||
private static String hash(Path path) { return Revisions.hash(Filespace.io(() -> Files.readAllBytes(path))); }
|
||||
private static Path operation(Path root, State state) { return Filespace.resolve(root, ".ai-engineering/.local/sqlite-migration/" + state.operation()); }
|
||||
private static Path original(Path root, State state) { return operation(root, state).resolve("original"); }
|
||||
private static Path stage(Path root, State state) { return operation(root, state).resolve("stage"); }
|
||||
private State state(Path root) {
|
||||
Path path = Filespace.resolve(root, JOURNAL);
|
||||
return Files.exists(path) ? Documents.readJson(path, State.class) : null;
|
||||
}
|
||||
private void save(Path root, State state) {
|
||||
Path path = Filespace.resolve(root, JOURNAL); Filespace.directory(path.getParent());
|
||||
Filespace.write(path, Documents.json(state), Files.exists(path));
|
||||
}
|
||||
public static void requireStable(Path root) {
|
||||
var state = new StorageMigration().state(root);
|
||||
if (state != null && !List.of("APPLIED", "ROLLED_BACK").contains(state.phase()))
|
||||
throw ProtocolException.validation("SQLite migration is " + state.phase() + "; use aie storage migrate --recover or --rollback --expect " + state.fingerprint());
|
||||
}
|
||||
private TreeMap<String, String> capture(Path root) {
|
||||
var hashes = new TreeMap<String, String>();
|
||||
Filespace.io(() -> {
|
||||
Files.walkFileTree(Filespace.resolve(root, ".ai-engineering"), new SimpleFileVisitor<>() {
|
||||
@Override public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attributes) {
|
||||
Filespace.resolve(root, relative(root, path));
|
||||
return path.equals(root.resolve(".ai-engineering/.local")) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
|
||||
}
|
||||
@Override public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
|
||||
Path safe = Filespace.resolve(root, relative(root, path));
|
||||
if (!attributes.isRegularFile()) throw ProtocolException.validation("Unsupported migration source: " + path);
|
||||
hashes.put(relative(root, path), hash(safe)); return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
return null;
|
||||
});
|
||||
for (String name : List.of("AGENTS.md", ".gitignore")) {
|
||||
Path path = Filespace.resolve(root, name);
|
||||
if (Files.exists(path)) {
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.validation("Invalid bootstrap source: " + name);
|
||||
hashes.put(name, hash(path));
|
||||
}
|
||||
}
|
||||
return hashes;
|
||||
}
|
||||
public Report preview(Path root) {
|
||||
State state = state(root);
|
||||
if (state != null && !state.phase().equals("ROLLED_BACK")) return report(root, state, List.of());
|
||||
var issues = new ArrayList<String>(); var hashes = new TreeMap<String, String>(); int count = 0;
|
||||
try {
|
||||
if (SqliteDatabase.active(root)) return new Report(1, true, "ALREADY_SQLITE", null, new WorkService().list(root).size(), null, List.of(), "No conversion required.");
|
||||
if (Files.exists(SqliteDatabase.path(root))) throw ProtocolException.validation("Unselected database already exists; inspect it before migration");
|
||||
ProtocolGuide.requireSupportedVersion(root);
|
||||
var validation = new VerificationService().project(root); issues.addAll(validation.issues());
|
||||
count = new WorkService().list(root).size(); hashes = capture(root);
|
||||
} catch (RuntimeException failure) { issues.add(failure.getMessage()); }
|
||||
return new Report(1, issues.isEmpty(), "LEGACY", Revisions.hash(Documents.json(hashes)), count, null, issues,
|
||||
"Review this preview; apply with storage migrate --apply --expect <fingerprint>. No consumer is migrated automatically.");
|
||||
}
|
||||
private Report report(Path root, State state, List<String> issues) {
|
||||
int count = (int) state.sourceHashes().keySet().stream().filter(path -> path.matches("\\.ai-engineering/works/WRK-[^/]+/work\\.md")).count();
|
||||
return new Report(1, issues.isEmpty(), state.phase(), state.fingerprint(), count, relative(root, original(root, state)), issues,
|
||||
state.phase().equals("APPLIED") ? "SQLite active; originals retained. Native installation is unchanged."
|
||||
: "Use storage migrate --recover or --rollback --expect " + state.fingerprint());
|
||||
}
|
||||
public Report apply(Path root, String expected) {
|
||||
return Filespace.lockedLegacy(root, () -> {
|
||||
State previous = state(root);
|
||||
if (previous != null && !previous.phase().equals("ROLLED_BACK")) {
|
||||
expect(previous, expected);
|
||||
if (previous.phase().equals("APPLIED")) { removeStage(stage(root, previous)); return report(root, previous, List.of()); }
|
||||
throw ProtocolException.validation("Interrupted migration; use --recover or --rollback with its fingerprint");
|
||||
}
|
||||
var preview = preview(root);
|
||||
if (!preview.valid() || !preview.phase().equals("LEGACY")) throw ProtocolException.validation("Migration preview is not applicable: " + preview.issues());
|
||||
if (!Objects.equals(preview.fingerprint(), expected)) throw ProtocolException.validation("Migration preview changed; preview again");
|
||||
State current = new State(UUID.randomUUID().toString(), "PREPARING", expected, capture(root), Map.of(), null);
|
||||
save(root, current);
|
||||
try { return prepareAndActivate(root, current); }
|
||||
catch (RuntimeException failure) { throw interrupted(current, failure); }
|
||||
});
|
||||
}
|
||||
private ProtocolException interrupted(State state, RuntimeException failure) {
|
||||
return new ProtocolException(failure instanceof ProtocolException p ? p.exitCode() : 1,
|
||||
"Migration interrupted; originals retained. Use storage migrate --recover or --rollback --expect " + state.fingerprint() + ": " + failure.getMessage());
|
||||
}
|
||||
private void expect(State state, String expected) {
|
||||
if (!Objects.equals(expected, state.fingerprint())) throw ProtocolException.validation("Expected fingerprint differs from the migration journal");
|
||||
}
|
||||
public Report recover(Path root, String expected, boolean rollback) {
|
||||
return Filespace.lockedLegacy(root, () -> {
|
||||
State current = state(root);
|
||||
if (current == null) throw ProtocolException.missing("No SQLite migration journal; run preview first");
|
||||
expect(current, expected);
|
||||
if (rollback) return rollback(root, current);
|
||||
if (current.phase().equals("APPLIED")) { removeStage(stage(root, current)); return report(root, current, List.of()); }
|
||||
if (current.phase().equals("ROLLED_BACK")) throw ProtocolException.validation("Migration rolled back; preview before a new application");
|
||||
try { return current.databaseHash() == null ? prepareAndActivate(root, current) : activate(root, current); }
|
||||
catch (RuntimeException failure) { throw interrupted(current, failure); }
|
||||
});
|
||||
}
|
||||
private void copyChecked(Path fromRoot, Path toRoot, Map<String, String> hashes) {
|
||||
for (var entry : hashes.entrySet()) {
|
||||
Path source = Filespace.resolve(fromRoot, entry.getKey()), target = Filespace.resolve(toRoot, entry.getKey());
|
||||
if (!hash(source).equals(entry.getValue())) throw ProtocolException.validation("Migration source changed: " + entry.getKey());
|
||||
Filespace.directory(target.getParent());
|
||||
if (Files.exists(target)) {
|
||||
if (!hash(target).equals(entry.getValue())) throw ProtocolException.validation("Migration safety copy differs: " + target);
|
||||
} else Filespace.writeBytes(target, Filespace.io(() -> Files.readAllBytes(source)), false);
|
||||
}
|
||||
}
|
||||
private void removeStage(Path directory) {
|
||||
if (!Files.exists(directory)) return;
|
||||
try (var paths = Filespace.io(() -> Files.walk(directory))) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
if (!path.equals(directory)) Filespace.resolve(directory, relative(directory, path));
|
||||
Filespace.io(() -> { Files.delete(path); return null; });
|
||||
}
|
||||
}
|
||||
}
|
||||
private Report prepareAndActivate(Path root, State state) {
|
||||
if (!capture(root).equals(state.sourceHashes())) throw ProtocolException.validation("Legacy source changed since preview; rollback and preview again");
|
||||
Path originals = original(root, state); Filespace.directory(originals);
|
||||
copyChecked(root, originals, state.sourceHashes());
|
||||
Filespace.directory(originals.resolve(".ai-engineering/works"));
|
||||
boundary.accept("BACKUP_READY");
|
||||
Path staging = stage(root, state); removeStage(staging); Filespace.directory(staging);
|
||||
var config = new ProjectService().load(originals);
|
||||
new ProjectService().initializeSqlite(staging, config.project().name(), false);
|
||||
Filespace.write(staging.resolve(".ai-engineering/ai-engineering.yaml"), Documents.yaml(
|
||||
new ProjectConfig(1, config.project(), config.repositories(), config.agents(), "sqlite")), true);
|
||||
// Provenance paths have the same project-relative spelling before and after activation.
|
||||
Path stageOriginals = Filespace.resolve(staging, relative(root, originals)); Filespace.directory(stageOriginals);
|
||||
copyChecked(originals, stageOriginals, state.sourceHashes());
|
||||
var legacyWorks = new WorkService().list(originals);
|
||||
var payloads = new TreeMap<String, String>();
|
||||
state.sourceHashes().forEach((path, digest) -> { if (path.startsWith(".ai-engineering/works/")) payloads.put(path, digest); });
|
||||
copyChecked(originals, staging, payloads);
|
||||
for (var work : legacyWorks) {
|
||||
Path folder = staging.resolve(".ai-engineering/works/" + new WorkService().folder(originals, work.id()).getFileName());
|
||||
for (String directory : List.of("discussions", "decisions", "plans", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
|
||||
Filespace.directory(Filespace.resolve(folder, directory));
|
||||
}
|
||||
importRecords(root, staging, originals, state, legacyWorks);
|
||||
for (var work : legacyWorks) {
|
||||
var validation = new VerificationService().work(staging, work.id());
|
||||
if (!validation.valid()) throw ProtocolException.validation("Staged " + work.id() + ": " + validation.issues());
|
||||
}
|
||||
new EpicService().definitions(staging);
|
||||
SqliteDatabase.checkpoint(staging);
|
||||
state = new State(state.operation(), "STAGED", state.fingerprint(), state.sourceHashes(), Map.of(), hash(SqliteDatabase.path(staging)));
|
||||
save(root, state); boundary.accept("STAGE_VALIDATED");
|
||||
return activate(root, state);
|
||||
}
|
||||
private <T> void record(Path destination, Path originals, State state, String work, String kind, String id,
|
||||
Path source, Class<T> type, String body) {
|
||||
T latest = Documents.readMarkdownDocument(source, type, body);
|
||||
var tree = Documents.jsonTree(latest); int last = tree.hasNonNull("revision") ? tree.get("revision").intValue() : 1;
|
||||
for (int revision = 1; revision <= last; revision++) {
|
||||
Path file = revision == last ? source : source.getParent().resolve(".history/" + id + "/r%04d.md".formatted(revision));
|
||||
T value = Documents.readMarkdownDocument(file, type, body);
|
||||
int version = Documents.metadata(file).has("documentVersion") ? Documents.metadata(file).get("documentVersion").intValue() : 1;
|
||||
SqliteRecords.put(destination, work, kind, id, value, type, revision != 1, version);
|
||||
if (!Objects.equals(value, SqliteRecords.get(destination, work, kind, id, revision, type)))
|
||||
throw ProtocolException.validation("Typed migration comparison failed: " + id);
|
||||
provenance(destination, work, kind, id, revision, ".ai-engineering/.local/sqlite-migration/" + state.operation() + "/original/" + relative(originals, file), hash(file));
|
||||
}
|
||||
}
|
||||
private void provenance(Path root, String work, String kind, String id, int revision, String source, String digest) {
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("UPDATE record_format SET original_path=?,original_sha256=? WHERE work_id=? AND kind=? AND local_id=? AND revision=?")) {
|
||||
statement.setString(1, source); statement.setString(2, digest); statement.setString(3, work); statement.setString(4, kind); statement.setString(5, id); statement.setInt(6, revision);
|
||||
if (statement.executeUpdate() != 1) throw ProtocolException.validation("Missing migration provenance target");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
private void importRecords(Path root, Path staging, Path originals, State state, List<Work> all) {
|
||||
var works = new WorkService();
|
||||
SqliteDatabase.write(staging, connection -> {
|
||||
for (var work : all) {
|
||||
try (var identity = connection.prepareStatement("INSERT INTO work_identity VALUES (?)"); var location = connection.prepareStatement("INSERT INTO work_location VALUES (?,?)")) {
|
||||
identity.setString(1, work.id()); identity.executeUpdate(); location.setString(1, work.id());
|
||||
location.setString(2, works.folder(originals, work.id()).getFileName().toString()); location.executeUpdate();
|
||||
}
|
||||
}
|
||||
for (var work : all) {
|
||||
Path folder = works.folder(originals, work.id());
|
||||
for (String id : work.discussions()) record(staging, originals, state, work.id(), "discussion", id, folder.resolve("discussions/" + id + ".md"), DiscussionEntry.class, "text");
|
||||
for (String id : work.topics()) record(staging, originals, state, work.id(), "topic", id, folder.resolve("topics/" + id + ".md"), Topic.class, "description");
|
||||
for (String id : work.surveys()) record(staging, originals, state, work.id(), "survey", id, folder.resolve("surveys/" + id + ".md"), Survey.class, "description");
|
||||
for (String id : work.dispositions()) record(staging, originals, state, work.id(), "disposition", id, folder.resolve("dispositions/" + id + ".md"), Disposition.class, "reason");
|
||||
for (String id : work.decisions()) record(staging, originals, state, work.id(), "decision", id, folder.resolve("decisions/" + id + ".md"), Decision.class, "text");
|
||||
for (String id : work.plans()) record(staging, originals, state, work.id(), "plan", id, folder.resolve("plans/" + id + ".md"), Plan.class, "description");
|
||||
for (String id : work.agentRuns()) record(staging, originals, state, work.id(), "run", id, folder.resolve("agent-runs/" + id + ".md"), AgentRun.class, "task");
|
||||
if (work.epic()) record(staging, originals, state, work.id(), "epic", work.id(), folder.resolve("epic/" + work.id() + ".md"), Epic.class, "reason");
|
||||
for (String id : work.artifacts()) {
|
||||
var artifact = Documents.read(folder.resolve("artifacts/evidence/" + id + "/artifact.yaml"), Artifact.class);
|
||||
SqliteRecords.put(staging, work.id(), "artifact", id, artifact, Artifact.class, false, 1);
|
||||
try (var statement = connection.prepareStatement("INSERT INTO artifact_lifecycle(work_id,artifact_id,state) VALUES (?,?,'RETAINED_LEGACY')")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, id); statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var work : all) {
|
||||
record(staging, originals, state, work.id(), "work", work.id(), works.folder(originals, work.id()).resolve("work.md"), Work.class, null);
|
||||
for (var completion : work.completions()) try (var statement = connection.prepareStatement("INSERT INTO quality_delivery VALUES (?,?,0)")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, completion.at()); statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
Path counter = originals.resolve(".ai-engineering/works/.sequence.yaml");
|
||||
long highWater = Files.exists(counter) ? Documents.read(counter, WorkService.Sequence.class).number() : 0;
|
||||
highWater = Math.max(highWater, all.stream().mapToLong(work -> Work.number(work.id())).max().orElse(0));
|
||||
try (var statement = connection.prepareStatement("UPDATE identity_sequence SET high_water=? WHERE scope='project' AND kind='work'")) {
|
||||
statement.setLong(1, highWater); statement.executeUpdate();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
private Report activate(Path root, State state) {
|
||||
var observed = capture(root);
|
||||
observed.keySet().removeIf(path -> path.matches("\\.ai-engineering/aie\\.db(?:-wal|-shm|-journal)?"));
|
||||
for (var entry : observed.entrySet()) {
|
||||
if (!entry.getValue().equals(state.sourceHashes().get(entry.getKey())) && !entry.getValue().equals(state.publishedHashes().get(entry.getKey())))
|
||||
throw ProtocolException.validation("Source changed before activation: " + entry.getKey() + "; rollback and preview again");
|
||||
}
|
||||
for (String path : state.sourceHashes().keySet()) if (!observed.containsKey(path)) throw ProtocolException.validation("Source disappeared before activation: " + path);
|
||||
Path originals = original(root, state), staging = stage(root, state);
|
||||
var published = new TreeMap<String, String>(); ProtocolGuide.entries(root).forEach((path, text) -> published.put(path, Revisions.hash(text)));
|
||||
var config = new ProjectService().load(originals);
|
||||
var sqlite = new ProjectConfig(1, config.project(), config.repositories(), config.agents(), "sqlite");
|
||||
published.put(".ai-engineering/ai-engineering.yaml", Revisions.hash(Documents.yaml(sqlite)));
|
||||
published.put(GUARD, Revisions.hash(GUARD_TEXT));
|
||||
state = new State(state.operation(), "ACTIVATING", state.fingerprint(), state.sourceHashes(), published, state.databaseHash()); save(root, state);
|
||||
ProtocolGuide.install(root);
|
||||
Path guard = Filespace.resolve(root, GUARD);
|
||||
if (Files.exists(guard)) { if (!Filespace.read(guard).equals(GUARD_TEXT)) throw ProtocolException.validation("Storage guard differs; inspect migration"); }
|
||||
else Filespace.write(guard, GUARD_TEXT, false);
|
||||
boundary.accept("ENTRY_GUARDED");
|
||||
Path database = SqliteDatabase.path(root);
|
||||
if (Files.exists(database)) {
|
||||
if (!hash(database).equals(state.databaseHash())) throw ProtocolException.validation("Published database differs; inspect before recovery");
|
||||
} else {
|
||||
Path prepared = SqliteDatabase.path(staging);
|
||||
if (!hash(prepared).equals(state.databaseHash())) throw ProtocolException.validation("Prepared database changed");
|
||||
Filespace.writeBytes(database, Filespace.io(() -> Files.readAllBytes(prepared)), false);
|
||||
}
|
||||
boundary.accept("DATABASE_PUBLISHED");
|
||||
Filespace.write(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), Documents.yaml(sqlite), true);
|
||||
boundary.accept("ACTIVATED");
|
||||
var validation = new VerificationService().project(root);
|
||||
if (!validation.valid()) throw ProtocolException.validation("Activated database needs inspection: " + validation.issues());
|
||||
save(root, state.phase("APPLIED")); removeStage(staging); return report(root, state.phase("APPLIED"), List.of());
|
||||
}
|
||||
private Report rollback(Path root, State state) {
|
||||
if (state.phase().equals("ROLLED_BACK")) return report(root, state, List.of());
|
||||
Path database = SqliteDatabase.path(root);
|
||||
if (state.publishedHashes().isEmpty() && !Files.exists(database)) {
|
||||
// No active file was changed: keep any subsequent legacy edits and abandon only our staging.
|
||||
save(root, state.phase("ROLLED_BACK")); removeStage(stage(root, state)); return report(root, state.phase("ROLLED_BACK"), List.of());
|
||||
}
|
||||
if (Files.exists(database)) {
|
||||
SqliteDatabase.checkpoint(root);
|
||||
if (state.databaseHash() == null || !hash(database).equals(state.databaseHash()))
|
||||
throw ProtocolException.validation("Database changed since activation; rollback would lose engineering memory. Keep SQLite and inspect deliberately");
|
||||
}
|
||||
// Refuse to overwrite unrelated post-migration edits, including human bootstrap changes.
|
||||
for (var entry : state.publishedHashes().entrySet()) {
|
||||
Path path = Filespace.resolve(root, entry.getKey());
|
||||
if (Files.exists(path) && !hash(path).equals(entry.getValue()) && !hash(path).equals(state.sourceHashes().get(entry.getKey())))
|
||||
throw ProtocolException.validation("Bootstrap changed since migration: " + entry.getKey());
|
||||
}
|
||||
Path originals = original(root, state);
|
||||
for (String path : state.sourceHashes().keySet()) {
|
||||
Path source = Filespace.resolve(originals, path), target = Filespace.resolve(root, path);
|
||||
if (!Files.exists(source)) {
|
||||
if (!Files.exists(target) || !hash(target).equals(state.sourceHashes().get(path))) throw ProtocolException.validation("Incomplete safety copy: " + path);
|
||||
continue;
|
||||
}
|
||||
if (!hash(source).equals(state.sourceHashes().get(path))) throw ProtocolException.validation("Safety copy changed: " + path);
|
||||
}
|
||||
for (String path : state.publishedHashes().keySet()) {
|
||||
Path target = Filespace.resolve(root, path);
|
||||
if (state.sourceHashes().containsKey(path)) Filespace.writeBytes(target, Filespace.io(() -> Files.readAllBytes(Filespace.resolve(originals, path))), true);
|
||||
else Filespace.io(() -> { Files.deleteIfExists(target); return null; });
|
||||
}
|
||||
for (String suffix : List.of("", "-wal", "-shm", "-journal")) {
|
||||
Path path = Filespace.resolve(root, ".ai-engineering/aie.db" + suffix);
|
||||
Filespace.io(() -> { Files.deleteIfExists(path); return null; });
|
||||
}
|
||||
save(root, state.phase("ROLLED_BACK")); removeStage(stage(root, state)); return report(root, state.phase("ROLLED_BACK"), List.of());
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,9 @@ public final class VerificationService {
|
||||
try { operation.run(); } catch (RuntimeException e) { issues.add(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); }
|
||||
}
|
||||
public ValidationReport project(Path root) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> projectSnapshot(root)) : projectSnapshot(root);
|
||||
}
|
||||
private ValidationReport projectSnapshot(Path root) {
|
||||
var issues = new ArrayList<String>();
|
||||
check(issues, () -> projects.validate(root));
|
||||
check(issues, () -> ProtocolGuide.validate(root));
|
||||
@@ -30,10 +33,24 @@ public final class VerificationService {
|
||||
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 number = SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.createStatement(); var row = statement.executeQuery("SELECT high_water FROM identity_sequence WHERE scope='project' AND kind='work'")) {
|
||||
if (!row.next()) throw ProtocolException.validation("Missing Work sequence"); return row.getLong(1);
|
||||
}
|
||||
}) : Documents.read(counter, WorkService.Sequence.class).number();
|
||||
long max = all.stream().mapToLong(w -> Work.number(w.id())).max().orElse(0);
|
||||
if (sequence.number() < max) issues.add("Work sequence is below the highest reserved ID");
|
||||
if (number < max) issues.add("Work sequence is below the highest reserved ID");
|
||||
}
|
||||
new EpicService().definitions(root);
|
||||
if (SqliteDatabase.active(root)) SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.createStatement(); var rows = statement.executeQuery("PRAGMA foreign_key_check")) {
|
||||
if (rows.next()) issues.add("SQLite foreign key violation: " + rows.getString(1));
|
||||
}
|
||||
try (var statement = connection.createStatement(); var rows = statement.executeQuery("PRAGMA quick_check")) {
|
||||
while (rows.next()) if (!"ok".equals(rows.getString(1))) issues.add("SQLite integrity: " + rows.getString(1));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
all.forEach(w -> issues.addAll(work(root, w.id()).issues()));
|
||||
});
|
||||
for (String directory : List.of("works", "contracts", ".local"))
|
||||
@@ -41,11 +58,14 @@ public final class VerificationService {
|
||||
return new ValidationReport(issues.isEmpty(), issues);
|
||||
}
|
||||
public ValidationReport work(Path root, String id) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> workSnapshot(root, id)) : workSnapshot(root, id);
|
||||
}
|
||||
private ValidationReport workSnapshot(Path root, String id) {
|
||||
var issues = new ArrayList<String>();
|
||||
check(issues, () -> ProtocolGuide.validate(root));
|
||||
check(issues, () -> {
|
||||
Work work = works.load(root, id); Path folder = works.folder(root, id);
|
||||
check(issues, () -> new EpicService().definitions(root));
|
||||
check(issues, () -> new EpicService().validateSelected(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());
|
||||
@@ -95,6 +115,12 @@ public final class VerificationService {
|
||||
}
|
||||
}));
|
||||
check(issues, () -> artifacts.validate(root, id));
|
||||
if (SqliteDatabase.active(root)) check(issues, () -> {
|
||||
var owned = Map.of("discussion", work.discussions(), "decision", work.decisions(), "plan", work.plans(),
|
||||
"topic", work.topics(), "survey", work.surveys(), "disposition", work.dispositions(), "run", work.agentRuns(), "artifact", work.artifacts());
|
||||
for (var entry : owned.entrySet()) if (!new HashSet<>(SqliteRecords.ids(root, entry.getKey(), id)).equals(new HashSet<>(entry.getValue())))
|
||||
issues.add("Unreferenced or missing SQLite records: " + entry.getKey());
|
||||
});
|
||||
check(issues, () -> new net.intrepid.aiengineering.legacyimport.DiscussionImportService().receipts(root, id));
|
||||
check(issues, () -> new TopicService().views(root, id));
|
||||
check(issues, () -> new SurveyService().list(root, id));
|
||||
@@ -120,6 +146,7 @@ public final class VerificationService {
|
||||
if (!work.artifacts().containsAll(criterion.evidence())) issues.add("Missing completion evidence for criterion " + criterion.criterion());
|
||||
check(issues, () -> new EpicCoordinator().validateHistory(root, work));
|
||||
check(issues, () -> new PlanCoordinator().validateHistory(root, work));
|
||||
check(issues, () -> new QualityGates().validateHistory(root, work));
|
||||
if (work.status() == Work.Status.COMPLETED) check(issues, () -> {
|
||||
if (work.completions().isEmpty()) { issues.add("Completed Work has no verified completion record; reopen it to record evidence"); return; }
|
||||
var completion = work.completions().getLast();
|
||||
@@ -155,6 +182,7 @@ public final class VerificationService {
|
||||
}
|
||||
ValidationReport localReadiness(Path root, String id) {
|
||||
var issues = new ArrayList<>(work(root, id).issues());
|
||||
check(issues, () -> issues.addAll(new QualityGates().pending(root, id)));
|
||||
check(issues, () -> {
|
||||
Work work = works.load(root, id);
|
||||
if (work.guidance() != null) check(issues, () -> work.guidance().requireMode());
|
||||
@@ -173,6 +201,7 @@ public final class VerificationService {
|
||||
/** Pending protocol commitments; neither invokes models nor interprets prose. */
|
||||
List<String> executionPending(Path root, String id) {
|
||||
var issues = new ArrayList<String>();
|
||||
check(issues, () -> issues.addAll(new QualityGates().pending(root, id)));
|
||||
var guided = works.load(root, id).guidance();
|
||||
if (guided != null) check(issues, guided::requireMode);
|
||||
if (!outstanding(root, id).isEmpty()) issues.add("Resolve outstanding questions and issues explicitly");
|
||||
@@ -229,6 +258,7 @@ public final class VerificationService {
|
||||
if (index > work.acceptanceCriteria().size() || results.containsKey(index)) throw ProtocolException.validation("Unknown or duplicate criterion: " + index);
|
||||
var evidence = List.of(mapping.substring(mapping.indexOf('=') + 1).split(","));
|
||||
if (!work.artifacts().containsAll(evidence)) throw ProtocolException.validation("Unknown criterion evidence: " + mapping);
|
||||
artifacts.requireAvailable(root, id, evidence);
|
||||
results.put(index, new Work.CriterionResult(index, work.acceptanceCriteria().get(index - 1), evidence));
|
||||
}
|
||||
if (results.size() != work.acceptanceCriteria().size()) throw ProtocolException.validation("Every acceptance criterion needs an evidence mapping (--criterion N=ART-0001)");
|
||||
@@ -240,11 +270,17 @@ public final class VerificationService {
|
||||
if (!seen.add(path)) throw ProtocolException.invalid("Duplicate canonical integration: " + relative);
|
||||
integrations.add(new Work.Integration(root.relativize(path).toString().replace('\\', '/'), Revisions.hash(Filespace.io(() -> Files.readAllBytes(path)))));
|
||||
}
|
||||
works.recordCompletion(root, id, new Work.Completion(Instant.now().toString(), by, summary, true, scopeHash(root, work),
|
||||
recordCompletion(root, id, new Work.Completion(Instant.now().toString(), by, summary, true, scopeHash(root, work),
|
||||
List.copyOf(results.values()), integrations, noIntegrationReason));
|
||||
return notifyChange(root, id, requester, key);
|
||||
});
|
||||
}
|
||||
Work recordCompletion(Path root, String id, Work.Completion completion) {
|
||||
new QualityGates().freeze(root, works.load(root, id), completion.at());
|
||||
var completed = works.recordCompletion(root, id, completion);
|
||||
ArtifactLifecycle.prepareCompleted(root, id);
|
||||
return completed;
|
||||
}
|
||||
private EpicCoordinator.LifecycleResult notifyChange(Path root, String id, String requester, String requestId) {
|
||||
try {
|
||||
var propagation = new PlanCoordinator().reconcile(root, id, requester, requestId).propagation();
|
||||
@@ -252,7 +288,8 @@ public final class VerificationService {
|
||||
}
|
||||
catch (RuntimeException failure) {
|
||||
throw new ProtocolException(failure instanceof ProtocolException p ? p.exitCode() : 1,
|
||||
"Work change persisted for " + id + "; propagation needs inspection/retry with epic reconcile " + id + ": " + failure.getMessage());
|
||||
(SqliteDatabase.active(root) ? "Work transaction rolled back for " + id + "; inspect propagation: "
|
||||
: "Work change persisted for " + id + "; propagation needs inspection/retry with epic reconcile " + id + ": ") + failure.getMessage());
|
||||
}
|
||||
}
|
||||
public EpicCoordinator.LifecycleResult status(Path root, String id, Work.Status status, String by, String reason, String requester, String requestId) {
|
||||
@@ -283,6 +320,9 @@ public final class VerificationService {
|
||||
/** Read-only projection for human listings; the full JSON contracts remain unchanged. */
|
||||
public record Overview(Work work, String steps, ValidationReport validation, List<Action> nextActions) {}
|
||||
public List<Overview> overview(Path root, List<Work> selected) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> overviewSnapshot(root, selected)) : overviewSnapshot(root, selected);
|
||||
}
|
||||
private List<Overview> overviewSnapshot(Path root, List<Work> selected) {
|
||||
return selected.stream().map(w -> {
|
||||
var validation = work(root, w.id());
|
||||
String progress = "unavailable";
|
||||
@@ -297,11 +337,17 @@ public final class VerificationService {
|
||||
}).toList();
|
||||
}
|
||||
public ProjectStatus status(Path root, boolean all) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> statusSnapshot(root, all)) : statusSnapshot(root, all);
|
||||
}
|
||||
private ProjectStatus statusSnapshot(Path root, boolean all) {
|
||||
return new ProjectStatus(1, projects.load(root).project(), ProtocolGuide.installed(root), works.list(root).stream()
|
||||
.filter(w -> all || !w.archived()).map(w -> new WorkSummary(w.id(), w.title(), w.status(), w.archived(), work(root, w.id()), actions(root, w))).toList(),
|
||||
new CompatibilityService().inspect(root).summary());
|
||||
}
|
||||
public List<Action> nextActions(Path root, String id) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> nextActionsSnapshot(root, id)) : nextActionsSnapshot(root, id);
|
||||
}
|
||||
private List<Action> nextActionsSnapshot(Path root, String id) {
|
||||
var result = new ArrayList<Action>();
|
||||
if (!ProtocolGuide.installed(root)) result.add(new Action("ONBOARD", null, "Install the portable protocol entry instructions", "aie onboard"));
|
||||
var selected = id == null ? works.list(root).stream().filter(w -> !w.archived()).toList() : List.of(works.load(root, id));
|
||||
@@ -314,8 +360,15 @@ public final class VerificationService {
|
||||
String id = work.id(); var actions = new ArrayList<Action>();
|
||||
if (!validation.valid()) return List.of(new Action(work.epic() ? "RECONCILE_EPIC" : "REPAIR_PROTOCOL", id,
|
||||
String.join("; ", validation.issues()), work.epic() ? "aie epic reconcile " + id : "aie work validate " + id));
|
||||
if (ArtifactLifecycle.pending(root, id) > 0) actions.add(new Action("RECOVER_ARTIFACTS", id,
|
||||
"Finish interrupted retirement of validated temporary attachments", "aie artifact recover " + id));
|
||||
if (work.archived()) return List.of(new Action("REOPEN", id, "Reopen only when new work is needed", "aie work reopen " + id + " --help"));
|
||||
if (work.terminal()) return List.of(new Action("ARCHIVE", id, "Retain the completed or cancelled record", "aie work archive " + id + " --help"));
|
||||
if (work.terminal()) {
|
||||
actions.add(new Action("ARCHIVE", id, "Retain the completed or cancelled record", "aie work archive " + id + " --help"));
|
||||
return List.copyOf(actions);
|
||||
}
|
||||
for (var gate : new QualityGates().inspect(root, id)) if (!gate.satisfied())
|
||||
actions.add(new Action("EVALUATE_GATE", id, gate.definition().key() + ": " + gate.pending(), "aie gate status " + id));
|
||||
if (work.epic()) {
|
||||
var evaluation = new EpicCoordinator().inspect(root, id);
|
||||
if (evaluation.canAutoComplete()) actions.add(new Action("RECONCILE_EPIC", id, "Apply the authorized aggregate condition", "aie epic reconcile " + id));
|
||||
@@ -391,8 +444,12 @@ public final class VerificationService {
|
||||
public record Context(int schemaVersion, Work work, List<DiscussionEntry> discussionHistory, List<Decision> decisions,
|
||||
List<String> outstandingQuestions, List<Artifact> artifacts, List<Plan> plans, String protocolGuide,
|
||||
List<TopicService.View> topics, List<Survey> surveys, List<Disposition> dispositions, List<AgentService.View> agentRuns,
|
||||
ProjectConfig.Agents agents, EpicCoordinator.Evaluation epic, String parentEpic, PlanCoordinator.Evaluation consolidation, String guidanceInstructions) {}
|
||||
ProjectConfig.Agents agents, EpicCoordinator.Evaluation epic, String parentEpic, PlanCoordinator.Evaluation consolidation, String guidanceInstructions,
|
||||
List<QualityGates.View> gates, java.util.Map<String, String> artifactStates) {}
|
||||
public Context context(Path root, String id) {
|
||||
return SqliteDatabase.active(root) ? SqliteDatabase.read(root, connection -> contextSnapshot(root, id)) : contextSnapshot(root, id);
|
||||
}
|
||||
private Context contextSnapshot(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);
|
||||
@@ -400,7 +457,12 @@ public final class VerificationService {
|
||||
new TopicService().views(root, id), new SurveyService().list(root, id), new DispositionService().list(root, id), new AgentService().views(root, id), projects.load(root).agents(),
|
||||
works.load(root, id).epic() ? new EpicCoordinator().inspect(root, id) : null, new EpicService().parent(root, id), new PlanCoordinator().inspect(root, id),
|
||||
works.load(root, id).guidance() == null ? "Historical Work without guidance: preserve recorded authority; adopt explicitly with work guidance before applying the new contract."
|
||||
: works.load(root, id).guidance().instructions());
|
||||
: works.load(root, id).guidance().instructions(), new QualityGates().inspect(root, id), artifactStates(root, id));
|
||||
}
|
||||
private java.util.Map<String, String> artifactStates(Path root, String id) {
|
||||
var states = new LinkedHashMap<String, String>();
|
||||
for (var artifact : artifacts.list(root, id)) states.put(artifact.id(), ArtifactLifecycle.state(root, id, artifact.id()));
|
||||
return Collections.unmodifiableMap(states);
|
||||
}
|
||||
private List<String> outstanding(Path root, String id) {
|
||||
var all = new ArrayList<>(outstanding(discussions.list(root, id)));
|
||||
@@ -431,6 +493,8 @@ public final class VerificationService {
|
||||
section(result, "Plans and execution steps", yaml(context.plans()));
|
||||
section(result, "Outstanding questions", items(context.outstandingQuestions()));
|
||||
section(result, "Artifact references (paths relative to Work)", yaml(context.artifacts()));
|
||||
section(result, "Artifact availability", yaml(context.artifactStates()));
|
||||
section(result, "Quality gates", yaml(context.gates()));
|
||||
section(result, "Completion records", yaml(w.completions()));
|
||||
section(result, "Plan consolidation", yaml(context.consolidation()));
|
||||
section(result, "Lifecycle history", yaml(w.events()));
|
||||
|
||||
@@ -11,7 +11,7 @@ public final class EpicService {
|
||||
private final WorkService works = new WorkService();
|
||||
public Path path(Path root, String id) { Work.identifier(id, "WRK"); return Filespace.resolve(works.folder(root, id), "epic/" + id + ".md"); }
|
||||
private Epic read(Path path, String id) {
|
||||
var value = Documents.readMarkdownDocument(path, Epic.class, "reason");
|
||||
var value = RecordStorage.read(path, Epic.class, "reason");
|
||||
if (!value.workId().equals(id)) throw ProtocolException.validation("EPIC identity mismatch: " + id);
|
||||
return value;
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public final class EpicService {
|
||||
var next = current;
|
||||
for (int revision = current.revision() - 1; revision >= 1; revision--) {
|
||||
Path previousPath = Revisions.history(works.folder(root, id), "epic", id, revision);
|
||||
String raw = Filespace.read(previousPath); Revisions.chain(next.revision(), next.previousHash(), revision + 1, raw);
|
||||
String raw = RecordStorage.raw(previousPath, Epic.class, "reason"); Revisions.chain(next.revision(), next.previousHash(), revision + 1, raw);
|
||||
var previous = read(previousPath, id);
|
||||
if (previous.revision() != revision) throw ProtocolException.validation("Invalid EPIC history revision");
|
||||
result.add(previous); next = previous;
|
||||
@@ -58,21 +58,48 @@ public final class EpicService {
|
||||
}
|
||||
}
|
||||
public Epic get(Path root, String id) {
|
||||
Work.identifier(id, "WRK"); works.load(root, id);
|
||||
Work.identifier(id, "WRK"); var work = works.load(root, id);
|
||||
if (SqliteDatabase.active(root)) {
|
||||
if (!work.epic()) throw ProtocolException.missing("Work is not an EPIC: " + id);
|
||||
var value = history(root, id).getLast();
|
||||
var links = SqliteDatabase.read(root, connection -> {
|
||||
var result = new TreeMap<String, Boolean>();
|
||||
try (var statement = connection.prepareStatement("SELECT child_work_id,important FROM epic_link WHERE parent_work_id=?")) {
|
||||
statement.setString(1, id);
|
||||
try (var rows = statement.executeQuery()) { while (rows.next()) result.put(rows.getString(1), rows.getBoolean(2)); }
|
||||
}
|
||||
return result;
|
||||
});
|
||||
var expected = new TreeMap<String, Boolean>(); value.children().forEach(link -> expected.put(link.workId(), link.important()));
|
||||
if (!links.equals(expected)) throw ProtocolException.validation("EPIC indexed links differ from policy: " + id);
|
||||
return value;
|
||||
}
|
||||
var result = definitions(root).get(id);
|
||||
if (result == null) throw ProtocolException.missing("Work is not an EPIC: " + id);
|
||||
return result;
|
||||
}
|
||||
public String parent(Path root, String child) {
|
||||
works.load(root, child);
|
||||
if (SqliteDatabase.active(root)) return SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT parent_work_id FROM epic_link WHERE child_work_id=?")) {
|
||||
statement.setString(1, child);
|
||||
try (var row = statement.executeQuery()) { return row.next() ? row.getString(1) : null; }
|
||||
}
|
||||
});
|
||||
return definitions(root).values().stream().filter(e -> e.children().stream().anyMatch(c -> c.workId().equals(child)))
|
||||
.map(Epic::workId).findFirst().orElse(null);
|
||||
}
|
||||
public void validateSelected(Path root, String id) {
|
||||
if (!SqliteDatabase.active(root)) { definitions(root); return; }
|
||||
var work = works.load(root, id);
|
||||
if (work.epic()) get(root, id);
|
||||
else if (SqliteRecords.current(root, id, "epic", id) != 0) throw ProtocolException.validation("Unreferenced EPIC definition: " + id);
|
||||
}
|
||||
private Epic publish(Path root, Epic old, Epic next) {
|
||||
if (old.equals(next)) return old;
|
||||
var proposed = new LinkedHashMap<>(definitions(root)); proposed.put(next.workId(), next); validateGraph(works.list(root), proposed);
|
||||
String raw = Filespace.read(path(root, old.workId()));
|
||||
Revisions.replace(works.folder(root, old.workId()), "epic", old.workId(), old.revision(), raw, Documents.markdownDocument(next, "reason"));
|
||||
String raw = RecordStorage.raw(path(root, old.workId()), Epic.class, "reason");
|
||||
RecordStorage.replaceRevision(works.folder(root, old.workId()), "epic", old.workId(), old.revision(), raw, Documents.markdownDocument(next, "reason"), Epic.class, "reason");
|
||||
works.touched(root, old.workId(), next.updatedAt()); return next;
|
||||
}
|
||||
public Epic configure(Path root, String id, Epic.Mode mode, String by, String reason) {
|
||||
@@ -83,7 +110,7 @@ public final class EpicService {
|
||||
return old.mode() == mode ? old : publish(root, old, old.changed(mode, old.children(), null, policyHash(root, id), by, reason));
|
||||
}
|
||||
var value = new Epic(1, id, mode, List.of(), null, 1, null, Instant.now().toString(), by, reason);
|
||||
Path target = path(root, id); Filespace.directory(target.getParent()); Documents.writeMarkdownDocument(target, value, "reason", false);
|
||||
Path target = path(root, id); Filespace.directory(target.getParent()); RecordStorage.write(target, value, Epic.class, "reason", false);
|
||||
works.markEpic(root, id); return value;
|
||||
});
|
||||
}
|
||||
@@ -127,12 +154,12 @@ public final class EpicService {
|
||||
return Revisions.hash(Documents.json(data));
|
||||
}
|
||||
public boolean authorized(Path root, Epic epic) { return epic.authorization() != null && epic.authorization().scopeHash().equals(authorityScope(root, epic)); }
|
||||
public String policyHash(Path root, String id) { return Revisions.hash(Filespace.read(path(root, id))); }
|
||||
public String policyHash(Path root, String id) { return Revisions.hash(RecordStorage.raw(path(root, id), Epic.class, "reason")); }
|
||||
public Epic byHash(Path root, String id, String hash) {
|
||||
var revisions = history(root, id);
|
||||
for (var value : revisions) {
|
||||
Path candidate = value.revision() == revisions.getLast().revision() ? path(root, id) : Revisions.history(works.folder(root, id), "epic", id, value.revision());
|
||||
if (Revisions.hash(Filespace.read(candidate)).equals(hash)) return value;
|
||||
if (Revisions.hash(RecordStorage.raw(candidate, Epic.class, "reason")).equals(hash)) return value;
|
||||
}
|
||||
throw ProtocolException.validation("Missing authorized EPIC policy history: " + id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package net.intrepid.aiengineering.work;
|
||||
|
||||
import net.intrepid.aiengineering.filesystem.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Work-specific ownership/allocation; field persistence uses typed columns and ordered rows. */
|
||||
final class SqliteWorkStore {
|
||||
private SqliteWorkStore() {}
|
||||
static Work load(Path root, String id) { return SqliteRecords.get(root, id, "work", id, 0, Work.class); }
|
||||
static List<Work> list(Path root) {
|
||||
return SqliteDatabase.read(root, connection -> SqliteRecords.ids(root, "work", null).stream()
|
||||
.map(id -> load(root, id)).sorted(Comparator.comparingLong(w -> Work.number(w.id()))).toList());
|
||||
}
|
||||
static String folder(Path root, String id) {
|
||||
return SqliteDatabase.read(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("SELECT folder FROM work_location WHERE work_id=?")) {
|
||||
statement.setString(1, id);
|
||||
try (var rows = statement.executeQuery()) {
|
||||
if (!rows.next()) throw ProtocolException.missing("Work not found: " + id);
|
||||
return rows.getString(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
static String allocate(Path root) {
|
||||
return SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("UPDATE identity_sequence SET high_water=high_water+1 WHERE scope='project' AND kind='work' AND high_water<? RETURNING high_water")) {
|
||||
statement.setLong(1, Work.MAX_NUMBER);
|
||||
try (var row = statement.executeQuery()) {
|
||||
if (!row.next()) throw ProtocolException.validation("Work ID space exhausted or sequence missing");
|
||||
return "WRK-%04X".formatted(row.getLong(1));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
static void register(Path root, Work work, String folder) {
|
||||
SqliteDatabase.write(root, connection -> {
|
||||
try (var statement = connection.prepareStatement("INSERT INTO work_identity VALUES (?)")) {
|
||||
statement.setString(1, work.id()); statement.executeUpdate();
|
||||
}
|
||||
try (var statement = connection.prepareStatement("INSERT INTO work_location VALUES (?,?)")) {
|
||||
statement.setString(1, work.id()); statement.setString(2, folder); statement.executeUpdate();
|
||||
}
|
||||
SqliteRecords.put(root, work.id(), "work", work.id(), work, Work.class, false, 1);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ 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) {
|
||||
if (SqliteDatabase.active(root)) return SqliteWorkStore.list(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());
|
||||
@@ -23,10 +24,15 @@ public final class WorkService {
|
||||
}
|
||||
public Work load(Path root, String id) {
|
||||
Work.identifier(id, "WRK");
|
||||
if (SqliteDatabase.active(root)) return SqliteWorkStore.load(root, id);
|
||||
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) {
|
||||
if (SqliteDatabase.active(root)) {
|
||||
Work.identifier(id, "WRK");
|
||||
return Filespace.resolve(workspace(root), SqliteWorkStore.folder(root, 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();
|
||||
@@ -45,6 +51,7 @@ public final class WorkService {
|
||||
public Work createPrepared(Path root, String title, String description, String goal, String motivation,
|
||||
List<String> constraints, List<String> criteria, List<String> repositories, String author,
|
||||
java.util.function.BiFunction<Path, Work, Work> prepare) {
|
||||
if (SqliteDatabase.active(root)) return createSqlite(root, title, description, goal, motivation, constraints, criteria, repositories, author, prepare);
|
||||
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.
|
||||
@@ -73,6 +80,40 @@ public final class WorkService {
|
||||
Filespace.moveDirectory(staging, target); return prepared;
|
||||
});
|
||||
}
|
||||
private Work createSqlite(Path root, String title, String description, String goal, String motivation,
|
||||
List<String> constraints, List<String> criteria, List<String> repositories, String author,
|
||||
java.util.function.BiFunction<Path, Work, Work> prepare) {
|
||||
var revisions = projects.revisions(root, repositories);
|
||||
return Filespace.locked(root, () -> {
|
||||
String id = SqliteWorkStore.allocate(root), 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, revisions, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), false,
|
||||
List.of(), List.of(), List.of(), List.of(), false);
|
||||
if (guidanceContract(root)) work = work.withGuidance(WorkGuidance.pending());
|
||||
String name = id + "-" + ProjectService.slug(title);
|
||||
Path target = Filespace.resolve(workspace(root), name);
|
||||
if (Files.exists(target)) throw ProtocolException.validation("Work files already exist; inspect the interrupted publication: " + target);
|
||||
Filespace.directory(target);
|
||||
SqliteDatabase.afterRollback(root, () -> {
|
||||
// Child publication recoveries run first. Preserve any unknown/nonempty residue.
|
||||
try (var paths = Filespace.io(() -> Files.walk(target))) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS))
|
||||
Filespace.io(() -> {
|
||||
try { Files.delete(path); } catch (DirectoryNotEmptyException retained) { /* Inspect retained files deliberately. */ }
|
||||
return null;
|
||||
});
|
||||
}
|
||||
});
|
||||
for (String dir : List.of("discussions", "decisions", "plans", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
|
||||
Filespace.directory(Filespace.resolve(target, dir));
|
||||
SqliteWorkStore.register(root, work, name);
|
||||
var prepared = prepare.apply(target, work);
|
||||
if (!prepared.id().equals(work.id()) || !prepared.createdAt().equals(work.createdAt()) || prepared.status() != Work.Status.OPEN)
|
||||
throw ProtocolException.validation("Prepared Work changed its identity or initial state");
|
||||
SqliteRecords.put(root, id, "work", id, prepared, Work.class, true, 1);
|
||||
return prepared;
|
||||
});
|
||||
}
|
||||
public record Sequence(int schemaVersion, String lastWork) {
|
||||
public Sequence {
|
||||
if (schemaVersion == 1) {
|
||||
@@ -88,7 +129,7 @@ public final class WorkService {
|
||||
}
|
||||
/** Called inside the caller's project lock after publishing the referenced file. */
|
||||
public void addReference(Path root, String id, String kind, String reference) {
|
||||
Documents.replaceFrontMatter(Filespace.resolve(folder(root, id), "work.md"), load(root, id).reference(kind, reference));
|
||||
RecordStorage.frontMatter(Filespace.resolve(folder(root, id), "work.md"), load(root, id).reference(kind, reference), Work.class);
|
||||
}
|
||||
public Work status(Path root, String id, Work.Status value) {
|
||||
return status(root, id, value, "human", "Status set to " + value);
|
||||
@@ -96,13 +137,13 @@ public final class WorkService {
|
||||
public Work status(Path root, String id, Work.Status value, String by, String reason) {
|
||||
return Filespace.locked(root, () -> {
|
||||
Work updated = load(root, id).withStatus(value, by, reason);
|
||||
Documents.replaceFrontMatter(Filespace.resolve(folder(root, id), "work.md"), updated); return updated;
|
||||
RecordStorage.frontMatter(Filespace.resolve(folder(root, id), "work.md"), updated, Work.class); return updated;
|
||||
});
|
||||
}
|
||||
public Work update(Path root, String id, Work.Update change) {
|
||||
return Filespace.locked(root, () -> {
|
||||
Work original = load(root, id); Work updated = original.update(change);
|
||||
if (!updated.equals(original)) Documents.replaceFrontMatter(Filespace.resolve(folder(root, id), "work.md"), updated);
|
||||
if (!updated.equals(original)) RecordStorage.frontMatter(Filespace.resolve(folder(root, id), "work.md"), updated, Work.class);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
@@ -145,7 +186,7 @@ public final class WorkService {
|
||||
public Work recordCompletion(Path root, String id, Work.Completion completion) {
|
||||
Work work = load(root, id).complete(completion); save(root, work); return work;
|
||||
}
|
||||
private void save(Path root, Work work) { Documents.replaceFrontMatter(Filespace.resolve(folder(root, work.id()), "work.md"), work); }
|
||||
private void save(Path root, Work work) { RecordStorage.frontMatter(Filespace.resolve(folder(root, work.id()), "work.md"), work, Work.class); }
|
||||
public Work archive(Path root, String id, String by, String reason) {
|
||||
return Filespace.locked(root, () -> { Work work = load(root, id).archive(by, reason); save(root, work); return work; });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user