feat: add agent coordination and automatic work completion

Add portable topics and surveys, decision approval history, execution plans, local Codex and Claude adapters, and general agent routing. Consolidate Plan and EPIC results through deterministic completion receipts, reviewed cancellation scope and recoverable reconciliation.

Track the completed WRK-0001 and WRK-0002 records, protocol documentation, source manifests and delivery evidence.

Validation: 117 tests including Modulith; GraalVM 25 native compilation, standalone smoke and ZIP/TAR verification on macOS ARM64; identical persisted context across JVM and native executions.
This commit is contained in:
Nilton Constantino
2026-11-14 01:12:21 +00:00
parent c84bb8d36f
commit bd2c9133da
355 changed files with 25740 additions and 154 deletions
@@ -6,6 +6,9 @@ import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.*;
import net.intrepid.aiengineering.artifact.*;
import net.intrepid.aiengineering.planning.*;
import net.intrepid.aiengineering.agent.*;
import java.time.Instant;
import java.nio.file.*;
import java.util.*;
@@ -15,19 +18,21 @@ public final class VerificationService {
private final DiscussionService discussions = new DiscussionService();
private final DecisionService decisions = new DecisionService();
private final ArtifactService artifacts = new ArtifactService();
private final PlanService plans = new PlanService();
private void check(List<String> issues, Runnable operation) {
try { operation.run(); } catch (RuntimeException e) { issues.add(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); }
}
public ValidationReport project(Path root) {
var issues = new ArrayList<String>();
check(issues, () -> projects.validate(root));
check(issues, () -> ProtocolGuide.validate(root));
check(issues, () -> {
var all = works.list(root);
Path counter = Filespace.resolve(works.workspace(root), ".sequence.yaml");
if (!all.isEmpty()) {
var sequence = Documents.read(counter, WorkService.Sequence.class);
long max = all.stream().mapToLong(w -> Long.parseLong(w.id().substring(4))).max().orElse(0);
if (sequence.lastWork() < max) issues.add("Work sequence is below the highest reserved ID");
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");
}
all.forEach(w -> issues.addAll(work(root, w.id()).issues()));
});
@@ -37,8 +42,10 @@ public final class VerificationService {
}
public ValidationReport work(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));
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());
@@ -54,13 +61,65 @@ public final class VerificationService {
seen.add(entry.id());
}
});
check(issues, () -> decisions.list(root, id).forEach(d -> {
if (!work.artifacts().containsAll(d.evidence())) issues.add("Missing decision evidence: " + d.id());
check(issues, () -> {
var all = decisions.list(root, id);
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());
if (d.revises() != null) {
var parent = byId.get(d.revises());
if (parent == null) issues.add("Missing revised decision: " + d.revises());
else if (d.approvalStatus() == Decision.Status.ACCEPTED && parent.approvalStatus() != Decision.Status.REJECTED
&& !d.id().equals(parent.supersededBy())) issues.add("Incomplete decision supersession: " + d.id());
}
if (d.supersededBy() != null) {
var replacement = byId.get(d.supersededBy());
if (replacement == null || !d.id().equals(replacement.revises())
|| (replacement.approvalStatus() != Decision.Status.ACCEPTED && replacement.approvalStatus() != Decision.Status.SUPERSEDED))
issues.add("Invalid superseding decision: " + d.id());
}
}
});
check(issues, () -> plans.list(root, id).forEach(plan -> {
if (!work.decisions().containsAll(plan.decisions())) issues.add("Missing plan decision: " + plan.id());
for (var step : plan.steps()) if (!work.artifacts().containsAll(step.evidence())) issues.add("Missing step evidence: " + step.id());
}));
check(issues, () -> artifacts.validate(root, id));
check(issues, () -> new TopicService().views(root, id));
check(issues, () -> new SurveyService().list(root, id));
check(issues, () -> new DispositionService().list(root, id));
check(issues, () -> new AgentService().history(root, id).forEach(run -> {
if (run.status() == AgentRun.Status.APPLYING) issues.add("Interrupted agent run requires inspection: " + run.id());
}));
for (var area : java.util.Map.of("topics", work.topics(), "surveys", work.surveys(), "dispositions", work.dispositions(), "agent-runs", work.agentRuns()).entrySet())
check(issues, () -> {
Path directory = Filespace.resolve(folder, area.getKey());
if (Files.exists(directory)) orphans(issues, folder, area.getKey(), area.getValue().stream().map(s -> s + ".md").toList());
else if (!area.getValue().isEmpty()) issues.add("Missing Work directory: " + area.getKey());
});
check(issues, () -> orphans(issues, folder, "discussions", work.discussions().stream().map(s -> s + ".md").toList()));
check(issues, () -> orphans(issues, folder, "decisions", work.decisions().stream().map(s -> s + ".md").toList()));
check(issues, () -> {
Path directory = Filespace.resolve(folder, "plans");
if (Files.exists(directory)) orphans(issues, folder, "plans", work.plans().stream().map(s -> s + ".md").toList());
else if (!work.plans().isEmpty()) issues.add("Missing Work directory: plans");
});
check(issues, () -> orphans(issues, folder, "artifacts/evidence", work.artifacts()));
for (var completion : work.completions()) for (var criterion : completion.criteria())
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));
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();
if (!completion.scopeHash().equals(scopeHash(root, work))) issues.add("Completed Work scope no longer matches its evidence snapshot");
if (completion.criteria().size() != work.acceptanceCriteria().size()) issues.add("Completion criterion count differs from Work scope");
for (var criterion : completion.criteria())
if (criterion.criterion() > work.acceptanceCriteria().size() || !work.acceptanceCriteria().get(criterion.criterion() - 1).equals(criterion.text()))
issues.add("Completion criterion differs from Work scope: " + criterion.criterion());
new EpicCoordinator().validateCurrent(root, work);
new PlanCoordinator().validateCurrent(root, work);
});
});
return new ValidationReport(issues.isEmpty(), issues);
}
@@ -70,17 +129,212 @@ public final class VerificationService {
if (!expected.contains(entry.getFileName().toString())) issues.add("Unreferenced protocol file: " + directory + "/" + entry.getFileName());
}
}
public record Context(int schemaVersion, Work work, List<DiscussionEntry> discussionHistory, List<DraftDecision> decisions,
List<String> outstandingQuestions, List<Artifact> artifacts) {}
/** Mechanical readiness only: the human still judges whether the evidence proves the criteria. */
public ValidationReport readiness(Path root, String id) {
var work = works.load(root, id);
if (!work.epic() && !work.plans().isEmpty()) {
var pending = new PlanCoordinator().inspect(root, id).pending();
return new ValidationReport(pending.isEmpty(), pending);
}
var issues = new ArrayList<>(localReadiness(root, id).issues());
check(issues, () -> {
if (works.load(root, id).epic()) issues.addAll(new EpicCoordinator().childPending(root, new EpicService().get(root, id)));
});
return new ValidationReport(issues.isEmpty(), issues.stream().distinct().toList());
}
ValidationReport localReadiness(Path root, String id) {
var issues = new ArrayList<>(work(root, id).issues());
check(issues, () -> {
Work work = works.load(root, id);
if (work.acceptanceCriteria().isEmpty() || work.acceptanceCriteria().stream().anyMatch(String::isBlank)) issues.add("Define explicit acceptance criteria");
if (!outstanding(root, id).isEmpty()) issues.add("Resolve outstanding questions and issues explicitly");
if (new SurveyService().list(root, id).stream().anyMatch(s -> s.questions().isEmpty())) issues.add("Empty surveys need questions before completion");
if (decisions.list(root, id).stream().anyMatch(d -> d.approvalStatus() == Decision.Status.DRAFT)) issues.add("Review draft decisions before completion");
for (var plan : plans.list(root, id)) {
if (plan.status() != Plan.Status.COMPLETED && !plan.excluded("PLAN")) issues.add("Unfinished plan: " + plan.id());
if (!plan.excluded("PLAN")) for (String decision : plan.decisions())
if (decisions.get(root, id, decision).approvalStatus() != Decision.Status.ACCEPTED) issues.add("Plan references a decision requiring reconsideration: " + decision);
}
});
return new ValidationReport(issues.isEmpty(), issues);
}
/** Pending protocol commitments; neither invokes models nor interprets prose. */
List<String> executionPending(Path root, String id) {
var issues = new ArrayList<String>();
if (!outstanding(root, id).isEmpty()) issues.add("Resolve outstanding questions and issues explicitly");
if (new SurveyService().list(root, id).stream().anyMatch(s -> s.questions().isEmpty())) issues.add("Empty surveys need questions before completion");
if (decisions.list(root, id).stream().anyMatch(d -> d.approvalStatus() == Decision.Status.DRAFT)) issues.add("Review draft decisions before completion");
for (var plan : plans.list(root, id)) if (!plan.excluded("PLAN")) for (String decision : plan.decisions())
if (decisions.get(root, id, decision).approvalStatus() != Decision.Status.ACCEPTED) issues.add("Plan references a decision requiring reconsideration: " + decision);
return List.copyOf(issues);
}
public String scopeHash(Path root, Work work) { return scopeHash(root, work, false); }
String epicInputHash(Path root, Work work) { return scopeHash(root, work, true); }
String planInputHash(Path root, Work work) { return scopeHash(root, work, true); }
private String scopeHash(Path root, Work work, boolean omitReceipts) {
var scope = new LinkedHashMap<String, Object>();
scope.put("id", work.id()); scope.put("title", work.title()); scope.put("description", work.description());
scope.put("goal", work.goal()); scope.put("motivation", work.motivation()); scope.put("constraints", work.constraints());
scope.put("acceptanceCriteria", work.acceptanceCriteria()); scope.put("repositories", work.repositories());
scope.put("discussions", discussions.list(root, work.id())); scope.put("decisions", decisions.list(root, work.id()));
scope.put("plans", plans.list(root, work.id()));
scope.put("artifacts", artifacts.list(root, work.id()).stream().filter(a -> !omitReceipts ||
(!a.origin().startsWith(EpicCoordinator.RECEIPT_ORIGIN) && !a.origin().startsWith(PlanCoordinator.RECEIPT_ORIGIN))).toList());
// Preserve historical completion digests for Works predating these optional records.
if (!work.topics().isEmpty()) scope.put("topics", new TopicService().list(root, work.id()));
if (!work.surveys().isEmpty()) scope.put("surveys", new SurveyService().list(root, work.id()));
if (!work.dispositions().isEmpty()) scope.put("dispositions", new DispositionService().list(root, work.id()));
if (!work.agentRuns().isEmpty()) scope.put("agentRuns", new AgentService().history(root, work.id()));
if (work.epic()) {
var definition = new EpicService().get(root, work.id()); scope.put("epic", definition);
scope.put("importantCompletions", new EpicCoordinator().completionSources(root, definition));
}
return Revisions.hash(Documents.json(scope));
}
public Work complete(Path root, String id, String by, String summary, boolean humanApproved, List<String> mappings,
List<String> integrationPaths, String noIntegrationReason) {
return completeWithPropagation(root, id, by, summary, humanApproved, mappings, integrationPaths, noIntegrationReason, by, null).work();
}
public EpicCoordinator.LifecycleResult completeWithPropagation(Path root, String id, String by, String summary,
boolean humanApproved, List<String> mappings, List<String> integrationPaths, String noIntegrationReason, String requester, String requestId) {
String key = EpicCoordinator.correlation(requestId); ProtocolException.text(requester, "requester");
return Filespace.locked(root, () -> {
var work = works.editable(root, id);
if (!humanApproved) throw ProtocolException.invalid("Explicit human approval is required");
var report = readiness(root, id);
if (!report.valid()) throw ProtocolException.validation(String.join("; ", report.issues()));
var results = new TreeMap<Integer, Work.CriterionResult>();
for (String mapping : mappings) {
if (!mapping.matches("[1-9][0-9]*=ART-[0-9]{4,9}(,ART-[0-9]{4,9})*")) throw ProtocolException.invalid("Expected criterion mapping N=ART-0001[,ART-0002]: " + mapping);
int index;
try { index = Integer.parseInt(mapping.substring(0, mapping.indexOf('='))); }
catch (NumberFormatException e) { throw ProtocolException.invalid("Invalid criterion index: " + mapping); }
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);
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)");
var integrations = new ArrayList<Work.Integration>(); var seen = new HashSet<Path>();
for (String relative : integrationPaths) {
Path path = Filespace.resolve(root, relative);
if (!Files.isRegularFile(path)) throw ProtocolException.invalid("Canonical integration must be an existing regular file: " + relative);
if (path.startsWith(Filespace.resolve(root, ".ai-engineering"))) throw ProtocolException.invalid("Integrate knowledge into canonical project files outside .ai-engineering");
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),
List.copyOf(results.values()), integrations, noIntegrationReason));
return notifyChange(root, id, requester, key);
});
}
private EpicCoordinator.LifecycleResult notifyChange(Path root, String id, String requester, String requestId) {
try {
var propagation = new PlanCoordinator().reconcile(root, id, requester, requestId).propagation();
return new EpicCoordinator.LifecycleResult(works.load(root, id), propagation);
}
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());
}
}
public EpicCoordinator.LifecycleResult status(Path root, String id, Work.Status status, String by, String reason, String requester, String requestId) {
String key = EpicCoordinator.correlation(requestId); ProtocolException.text(requester, "requester");
return Filespace.locked(root, () -> { new EpicService().definitions(root); works.status(root, id, status, by, reason); return notifyChange(root, id, requester, key); });
}
public EpicCoordinator.LifecycleResult reopen(Path root, String id, String by, String reason, String requester, String requestId) {
String key = EpicCoordinator.correlation(requestId); ProtocolException.text(requester, "requester");
return Filespace.locked(root, () -> {
new EpicService().definitions(root); works.reopen(root, id, by, reason);
// A deliberate reopening must remain open for replanning, rather than immediately auto-close.
if (works.load(root, id).epic()) new EpicService().revokeAuthorization(root, id, by, "Explicit reopening suspends automatic completion: " + reason);
return notifyChange(root, id, requester, key);
});
}
public EpicCoordinator.LifecycleResult update(Path root, String id, Work.Update change) {
return Filespace.locked(root, () -> { new EpicService().definitions(root); works.update(root, id, change); return notifyChange(root, id, "cli", null); });
}
public Work archive(Path root, String id, String by, String reason) {
var report = work(root, id);
if (!report.valid()) throw ProtocolException.validation(String.join("; ", report.issues()));
return works.archive(root, id, by, reason);
}
public record Action(String code, String workId, String message, String command) {}
public record WorkSummary(String id, String title, Work.Status status, boolean archived, ValidationReport validation, List<Action> nextActions) {}
public record ProjectStatus(int schemaVersion, ProjectConfig.Identity project, boolean onboarded, List<WorkSummary> works) {}
public ProjectStatus status(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());
}
public List<Action> nextActions(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));
selected.forEach(w -> result.addAll(actions(root, w))); return List.copyOf(result);
}
private List<Action> actions(Path root, Work work) {
String id = work.id(); var actions = new ArrayList<Action>();
var validation = work(root, id);
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 (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.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));
else if (evaluation.definition().mode() == Epic.Mode.RESULTS) {
if (!evaluation.authorizationCurrent()) actions.add(new Action("AUTHORIZE_EPIC", id, "Review policy, scopes and automatic completion authority", "aie epic authorize " + id + " --help"));
for (String pending : evaluation.pending()) actions.add(new Action("EPIC_PENDING", id, pending, "aie epic check " + id));
}
}
if (work.acceptanceCriteria().isEmpty()) actions.add(new Action("REFINE_SCOPE", id, "Define scope and acceptance criteria collaboratively", "aie work update " + id + " --help"));
for (String question : outstanding(root, id)) actions.add(new Action("RESPOND", id, question,
question.startsWith("SVY-") ? "aie survey show " + id + " " + question.substring(0, question.indexOf('/')) : "aie discussion add " + id + " --help"));
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()));
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"));
var done = plan.steps().stream().filter(s -> s.status() == Plan.Status.COMPLETED).map(Plan.Step::id).toList();
for (var step : plan.steps()) {
if (step.status() == Plan.Status.CANCELLED || step.status() == Plan.Status.COMPLETED) continue;
String code = step.status() == Plan.Status.BLOCKED ? "INVESTIGATE" : done.containsAll(step.dependsOn()) ? "EXECUTE_STEP" : "WAIT_DEPENDENCIES";
actions.add(new Action(code, id, plan.id() + "/" + step.id() + ": " + step.title(), "aie plan show " + id + " " + plan.id()));
}
if (!plan.steps().isEmpty() && plan.steps().stream().allMatch(s -> s.status() == Plan.Status.COMPLETED || s.status() == Plan.Status.CANCELLED))
actions.add(new Action("FINISH_PLAN", id, "Record the result of " + plan.id(), "aie plan status " + id + " " + plan.id() + " COMPLETED --help"));
}
if (!work.epic()) {
if (work.plans().isEmpty()) actions.add(new Action("CREATE_PLAN", id, "Define executable Plans; an empty set cannot auto-complete", "aie plan create " + id + " --help"));
else if (new PlanCoordinator().inspect(root, id).canAutoComplete()) actions.add(new Action("RECONCILE_WORK", id, "Consolidate completed Plans without consulting a model", "aie work reconcile " + id));
}
if (actions.isEmpty()) actions.add(new Action("REFINE_APPROACH", id, "Continue discussion or prepare a decision and proportional plan", "aie work context " + id));
return List.copyOf(actions);
}
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) {}
public Context context(Path root, String id) {
var report = work(root, id);
if (!report.valid()) throw ProtocolException.validation(String.join("; ", report.issues()));
var history = discussions.list(root, id);
return new Context(1, works.load(root, id), history, decisions.list(root, id), outstanding(root, id), artifacts.list(root, id), plans.list(root, id), ProtocolGuide.guide(root),
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));
}
private List<String> outstanding(Path root, String id) {
var all = new ArrayList<>(outstanding(discussions.list(root, id)));
for (var survey : new SurveyService().list(root, id)) for (var q : survey.pending()) all.add(survey.id() + "/" + q.id() + " [" + q.topicId() + "]: " + q.text());
return List.copyOf(all);
}
private List<String> outstanding(List<DiscussionEntry> history) {
var answered = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.RESPONSE || e.kind() == DiscussionEntry.Kind.CONCLUSION)
.map(DiscussionEntry::respondsTo).filter(Objects::nonNull).toList();
var outstanding = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.QUESTION || e.kind() == DiscussionEntry.Kind.ISSUE)
return history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.QUESTION || e.kind() == DiscussionEntry.Kind.ISSUE)
.filter(e -> !answered.contains(e.id())).map(e -> e.id() + ": " + e.text()).toList();
return new Context(1, works.load(root, id), history, decisions.list(root, id), outstanding, artifacts.list(root, id));
}
public String markdown(Context context) {
var w = context.work();
@@ -88,11 +342,23 @@ public final class VerificationService {
section(result, "Goal", w.goal()); section(result, "Description", w.description()); section(result, "Motivation", w.motivation());
section(result, "Constraints", items(w.constraints())); section(result, "Acceptance criteria", items(w.acceptanceCriteria()));
section(result, "Repository revisions at Work creation", yaml(w.repositories()));
section(result, "EPIC coordination", context.epic() == null ? context.parentEpic() == null ? "None recorded." : "Parent EPIC: " + context.parentEpic() : yaml(context.epic()));
section(result, "Discussion history and conclusions", discussionMarkdown(context.discussionHistory()));
section(result, "Discussion topics", yaml(context.topics()));
section(result, "Surveys and answer history", context.surveys().isEmpty() ? "None recorded." : String.join("\n", context.surveys().stream().map(this::surveyMarkdown).toList()));
section(result, "Proposal dispositions", yaml(context.dispositions()));
section(result, "Agent configuration", context.agents() == null ? "Not configured." : yaml(context.agents()));
section(result, "Agent run provenance (fixture adapters are explicit)", yaml(context.agentRuns()));
section(result, "Decisions (approval status is explicit)", decisionMarkdown(context.decisions()));
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, "Completion records", yaml(w.completions()));
section(result, "Plan consolidation", yaml(context.consolidation()));
section(result, "Lifecycle history", yaml(w.events()));
section(result, "Archive", Boolean.toString(w.archived()));
section(result, "Metadata", "Created: " + w.createdAt() + "\n\nUpdated: " + w.updatedAt() + "\n\nAuthor: " + w.author());
section(result, "Protocol guide", context.protocolGuide());
return result.toString();
}
public String discussionMarkdown(List<DiscussionEntry> entries) {
@@ -108,7 +374,21 @@ public final class VerificationService {
}
return out.toString();
}
private static String decisionMarkdown(List<DraftDecision> decisions) {
public String surveyMarkdown(Survey survey) {
var out = new StringBuilder("### " + survey.id() + " — " + survey.title() + "\n\n" + survey.description() + "\n");
for (var q : survey.questions()) {
out.append("\n#### ").append(q.id()).append(" [").append(q.topicId()).append("]\n\n").append(q.text()).append("\n\n");
for (var option : q.options()) out.append("- ").append(option.id()).append(". ").append(option.text()).append(option.id().equals(q.recommendedOption()) ? " (suggested)" : "").append('\n');
out.append("\nFree text is also accepted.\n");
var latest = survey.latest(q.id());
if (latest == null) out.append("\nPending answer.\n");
else out.append("\nLatest answer: ").append(latest.id()).append(" by ").append(latest.author()).append("\n\nChoices: ").append(latest.choices()).append("\n\n").append(latest.text()).append('\n');
for (var answer : survey.answers()) if (answer.questionId().equals(q.id()) && (latest == null || !answer.id().equals(latest.id())))
out.append("\nPrevious answer: ").append(answer.id()).append(" by ").append(answer.author()).append("\n\nChoices: ").append(answer.choices()).append("\n\n").append(answer.text()).append('\n');
}
return out.toString();
}
public String decisionMarkdown(List<Decision> decisions) {
if (decisions.isEmpty()) return "None recorded.";
var out = new StringBuilder();
for (var decision : decisions) {
@@ -120,6 +400,9 @@ public final class VerificationService {
subsection(out, "Alternatives", items(decision.alternatives())); subsection(out, "Rationale", decision.rationale());
subsection(out, "Risks", items(decision.risks())); subsection(out, "Acceptance criteria", items(decision.acceptanceCriteria()));
subsection(out, "Evidence", items(decision.evidence()));
subsection(out, "Discussion and details", decision.text());
subsection(out, "Revision and approvals", "Revision: " + decision.revision() + "\n\nUpdated by: " + decision.updatedBy()
+ "\n\nReason: " + decision.changeReason() + "\n\n" + yaml(decision.approvals()));
}
return out.toString();
}