feat: promote draft decisions when creating plans

Promote referenced drafts deterministically with system provenance, causal
Plan links, supersession history and recovery from publication failures.
Preserve direct human approval and historical records.

Add JVM and native regression coverage and update the portable protocol.
Record the WRK-0007 importer decision and six-step plan, and complete
WRK-0008 with verification evidence.
This commit is contained in:
2026-11-16 12:35:06 +00:00
parent 8572f43149
commit bc9fe8152c
101 changed files with 5322 additions and 14 deletions
@@ -15,7 +15,7 @@ public final class NativeHints implements RuntimeHintsRegistrar {
@Override public void registerHints(RuntimeHints hints, ClassLoader loader) {
for (Class<?> type : new Class<?>[]{ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class,
ProjectConfig.Access.class, ProjectService.Revision.class, Work.class, WorkService.Sequence.class, DiscussionEntry.class,
Decision.class, Decision.Approval.class, Plan.class, Plan.Step.class, Plan.Exclusion.class,
Decision.class, Decision.Approval.class, Decision.ApprovalOrigin.class, Plan.class, Plan.Step.class, Plan.Exclusion.class,
PlanCoordinator.PlanSource.class, PlanCoordinator.Receipt.class, PlanCoordinator.Evaluation.class,
PlanCoordinator.Result.class, PlanCoordinator.Mutation.class, Work.Aggregation.class,
Work.Event.class, Work.Completion.class, Work.CriterionResult.class, Work.Integration.class,
@@ -330,7 +330,7 @@ public final class EngineeringCli implements Runnable {
}
@Command(name = "plan", mixinStandardHelpOptions = true, description = "Maintain proportional implementation plans; execution remains external.")
public class PlanCommands {
@Command(name = "create", mixinStandardHelpOptions = true)
@Command(name = "create", mixinStandardHelpOptions = true, description = "Create a Plan and automatically promote referenced draft decisions without a model call.")
int create(@Parameters(index = "0") String work, @Option(names = "--title", required = true) String title,
@Option(names = "--description", defaultValue = "") String description, @Option(names = "--decision") List<String> decisions,
@Option(names = "--author", defaultValue = "human") String author) {
@@ -4,6 +4,7 @@ import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.work.Work;
import java.time.Instant;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonInclude;
public record Decision(int schemaVersion, String id, String workId, String title, String context,
String approach, List<String> alternatives, String rationale, List<String> risks, List<String> acceptanceCriteria,
@@ -11,10 +12,24 @@ public record Decision(int schemaVersion, String id, String workId, String title
Integer revision, String previousHash, String updatedAt, String updatedBy, String changeReason,
List<Approval> approvals, String revises, String supersededBy) {
public enum Status { DRAFT, ACCEPTED, REJECTED, SUPERSEDED }
public record Approval(Status status, String by, String reason, String at, boolean humanApproved) {
public enum ApprovalOrigin { DIRECT, SYSTEM_PLAN }
public record Approval(Status status, String by, String reason, String at, boolean humanApproved,
@JsonInclude(JsonInclude.Include.NON_NULL) ApprovalOrigin origin,
@JsonInclude(JsonInclude.Include.NON_NULL) String planId) {
public Approval(Status status, String by, String reason, String at, boolean humanApproved) {
this(status, by, reason, at, humanApproved, null, null);
}
public Approval {
Objects.requireNonNull(status); ProtocolException.text(by, "approval actor"); ProtocolException.text(reason, "approval reason"); Instant.parse(at);
if ((status == Status.ACCEPTED || status == Status.SUPERSEDED) && !humanApproved) throw ProtocolException.validation("Missing human approval attestation");
if (origin == ApprovalOrigin.SYSTEM_PLAN) {
Work.identifier(planId, "PLN");
if (humanApproved || !by.equals("system:planning") || (status != Status.ACCEPTED && status != Status.SUPERSEDED))
throw ProtocolException.validation("Invalid system Plan promotion provenance");
} else {
if (planId != null) throw ProtocolException.validation("Plan promotion requires SYSTEM_PLAN origin");
if ((status == Status.ACCEPTED || status == Status.SUPERSEDED) && !humanApproved)
throw ProtocolException.validation("Missing human approval attestation");
}
}
}
public Decision {
@@ -57,9 +72,17 @@ public record Decision(int schemaVersion, String id, String workId, String title
}
public Decision accept(String by, String reason, boolean humanApproved, String hash) {
if (!humanApproved) throw ProtocolException.invalid("--human-approved is required to record an explicit human approval");
requireAcceptable();
return transition(Status.ACCEPTED, by, reason, true, hash, null);
}
private void requireAcceptable() {
if (approvalStatus != Status.DRAFT) throw ProtocolException.invalid("Only a draft decision can be accepted");
if (context.isBlank() || approach.isBlank() || rationale.isBlank()) throw ProtocolException.validation("Acceptance needs context, approach and rationale");
return transition(Status.ACCEPTED, by, reason, true, hash, null);
}
public Decision acceptForPlan(String plan, String requester, String hash) {
requireAcceptable(); ProtocolException.text(requester, "Plan requester");
return transition(Status.ACCEPTED, "system:planning", "Creation of " + plan + " by " + requester + " promotes its draft decision",
false, hash, null, ApprovalOrigin.SYSTEM_PLAN, plan);
}
public Decision reject(String by, String reason, String hash) {
if (approvalStatus != Status.DRAFT) throw ProtocolException.invalid("Only a draft decision can be rejected");
@@ -69,8 +92,17 @@ public record Decision(int schemaVersion, String id, String workId, String title
if (approvalStatus != Status.ACCEPTED) throw ProtocolException.invalid("The revised decision is no longer accepted; review the current decision");
return transition(Status.SUPERSEDED, by, reason, true, hash, replacement);
}
public Decision supersedeForPlan(String replacement, String plan, String requester, String hash) {
if (approvalStatus != Status.ACCEPTED) throw ProtocolException.invalid("The revised decision is no longer accepted; review the current decision");
return transition(Status.SUPERSEDED, "system:planning", "Creation of " + plan + " by " + requester + " promotes replacement " + replacement,
false, hash, replacement, ApprovalOrigin.SYSTEM_PLAN, plan);
}
private Decision transition(Status target, String by, String reason, boolean humanApproved, String hash, String replacement) {
var history = new ArrayList<>(approvals); history.add(new Approval(target, by, reason, Instant.now().toString(), humanApproved));
return transition(target, by, reason, humanApproved, hash, replacement, null, null);
}
private Decision transition(Status target, String by, String reason, boolean humanApproved, String hash, String replacement,
ApprovalOrigin origin, String plan) {
var history = new ArrayList<>(approvals); history.add(new Approval(target, by, reason, Instant.now().toString(), humanApproved, origin, plan));
return snapshot(target, by, reason, hash, history, replacement);
}
private Decision snapshot(Status target, String by, String reason, String hash, List<Approval> history, String replacement) {
@@ -77,6 +77,69 @@ public final class DecisionService {
return accepted;
});
}
private record PlanChange(Decision old, Decision changed, String original, String replacement, Path current, Path history, boolean historyExisted) {}
/** Prepared under the caller's project lock. No decisions change during validation. */
public static final class PlanAcceptance {
private final List<PlanChange> changes;
private final List<PlanChange> attempted = new ArrayList<>();
private PlanAcceptance(List<PlanChange> changes) { this.changes = List.copyOf(changes); }
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());
}
}
public void rollback() {
for (var change : attempted.reversed()) {
String current = Filespace.read(change.current());
if (!current.equals(change.original()) && !current.equals(change.replacement()))
throw ProtocolException.validation("Concurrent edit during Plan promotion recovery: " + change.current());
if (!current.equals(change.original())) Filespace.write(change.current(), change.original(), true);
if (!change.historyExisted() && Files.exists(change.history())) {
if (!Filespace.read(change.history()).equals(change.original()))
throw ProtocolException.validation("Conflicting history during Plan promotion recovery: " + change.history());
Filespace.io(() -> { Files.delete(change.history()); return null; });
}
}
}
}
public PlanAcceptance preparePlanAcceptance(Path root, String workId, List<String> refs, String plan, String requester) {
var work = works.editable(root, workId); Work.identifier(plan, "PLN");
var selected = new LinkedHashMap<String, Decision>();
for (String id : refs) selected.put(id, get(root, workId, id));
var proposed = new LinkedHashMap<String, Decision>();
var originals = new HashMap<String, String>();
for (var old : selected.values()) {
if (old.approvalStatus() == Decision.Status.ACCEPTED) continue;
if (old.approvalStatus() != Decision.Status.DRAFT)
throw ProtocolException.invalid("Plan creation requires a draft or accepted decision: " + old.id());
evidence(work, old.evidence());
String original = Filespace.read(path(root, workId, old.id())); 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());
if (parent.approvalStatus() != Decision.Status.ACCEPTED && parent.approvalStatus() != Decision.Status.REJECTED)
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);
proposed.put(parent.id(), parent.supersedeForPlan(old.id(), plan, requester, Revisions.hash(parentOriginal)));
}
}
}
for (var old : selected.values())
if (proposed.getOrDefault(old.id(), old).approvalStatus() != Decision.Status.ACCEPTED)
throw ProtocolException.invalid("Plan cannot reference a decision superseded by its own creation: " + old.id());
var changes = new ArrayList<PlanChange>(); Path folder = works.folder(root, workId);
for (var next : proposed.values()) {
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);
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));
@@ -44,10 +44,31 @@ public final class PlanService {
}
public Plan create(Path root, String workId, String title, String description, List<String> refs, String author) {
return Filespace.locked(root, () -> {
var work = works.editable(root, workId); accepted(root, workId, refs); String id = works.nextReference(work.plans(), "PLN"), now = Instant.now().toString();
var work = works.editable(root, workId); String id = works.nextReference(work.plans(), "PLN"), now = Instant.now().toString();
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); Filespace.directory(path.getParent()); Documents.writeMarkdownDocument(path, plan, "description", false);
works.addReference(root, workId, "plans", id); return plan;
Path path = path(root, workId, id), folder = works.folder(root, workId), workPath = Filespace.resolve(folder, "work.md");
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);
Filespace.directory(path.getParent());
try {
promotions.publish(folder);
Filespace.write(path, document, false);
works.addReference(root, workId, "plans", id); return plan;
} catch (RuntimeException failure) {
try {
if (Files.exists(path)) {
if (!Filespace.read(path).equals(document)) throw ProtocolException.validation("Concurrent edit during Plan recovery: " + path);
Filespace.io(() -> { Files.delete(path); return null; });
}
promotions.rollback();
if (!Filespace.read(workPath).equals(originalWork)) Filespace.write(workPath, originalWork, true);
} catch (RuntimeException recovery) {
failure.addSuppressed(recovery);
throw new ProtocolException(4, "Plan creation interrupted; inspect " + workId + ": " + failure.getMessage() + "; recovery: " + recovery.getMessage());
}
throw failure;
}
});
}
private Plan mutate(Path root, String work, String id, String by, String reason, Function<Plan, Plan> mutation) {
@@ -66,6 +66,12 @@ public final class VerificationService {
var byId = new HashMap<String, Decision>(); all.forEach(d -> byId.put(d.id(), d));
for (var d : all) {
if (!work.artifacts().containsAll(d.evidence())) issues.add("Missing decision evidence: " + d.id());
for (var approval : d.approvals()) if (approval.origin() == Decision.ApprovalOrigin.SYSTEM_PLAN) {
String target = approval.status() == Decision.Status.SUPERSEDED ? d.supersededBy() : d.id();
if (!work.plans().contains(approval.planId())) issues.add("Missing promoting Plan for " + d.id() + ": " + approval.planId());
else if (!plans.history(root, id, approval.planId()).getFirst().decisions().contains(target))
issues.add("Promoting Plan does not reference its decision: " + d.id() + "/" + approval.planId());
}
if (d.revises() != null) {
var parent = byId.get(d.revises());
if (parent == null) issues.add("Missing revised decision: " + d.revises());
@@ -295,7 +301,7 @@ public final class VerificationService {
for (var survey : new SurveyService().list(root, id)) if (survey.questions().isEmpty())
actions.add(new Action("ADD_QUESTION", id, "Add questions with suggestions to " + survey.id(), "aie survey question " + id + " " + survey.id() + " --help"));
for (var decision : decisions.list(root, id)) if (decision.approvalStatus() == Decision.Status.DRAFT)
actions.add(new Action("REVIEW_DECISION", id, "Discuss and obtain human approval for " + decision.id(), "aie decision show " + id + " " + decision.id()));
actions.add(new Action("REVIEW_DECISION", id, "Review " + decision.id() + "; accept explicitly or create a Plan from it", "aie decision show " + id + " " + decision.id()));
for (var plan : plans.list(root, id)) {
if (plan.status() == Plan.Status.COMPLETED || plan.status() == Plan.Status.CANCELLED) continue;
if (plan.steps().isEmpty()) actions.add(new Action("ADD_STEP", id, "Add explicit steps to " + plan.id(), "aie plan step add " + id + " " + plan.id() + " --help"));