package net.intrepid.aiengineering.verification; import net.intrepid.aiengineering.filesystem.*; import net.intrepid.aiengineering.project.*; import net.intrepid.aiengineering.work.*; import net.intrepid.aiengineering.discussion.*; import net.intrepid.aiengineering.decision.*; import net.intrepid.aiengineering.artifact.*; import net.intrepid.aiengineering.planning.*; import net.intrepid.aiengineering.agent.*; import java.time.Instant; import java.nio.file.*; import java.util.*; public final class VerificationService { private final ProjectService projects = new ProjectService(); private final WorkService works = new WorkService(); private final DiscussionService discussions = new DiscussionService(); private final DecisionService decisions = new DecisionService(); private final ArtifactService artifacts = new ArtifactService(); private final PlanService plans = new PlanService(); private void check(List 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(); 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 -> 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())); }); for (String directory : List.of("works", "contracts", ".local")) check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(root, ".ai-engineering/" + directory))) issues.add("Missing project directory: " + directory); }); return new ValidationReport(issues.isEmpty(), issues); } public ValidationReport work(Path root, String id) { var issues = new ArrayList(); 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()); check(issues, () -> Filespace.resolve(root, revision.path())); } for (String directory : List.of("discussions", "decisions", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs")) check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(folder, directory))) issues.add("Missing Work directory: " + directory); }); check(issues, () -> { var entries = discussions.list(root, id); var seen = new HashSet(); for (var entry : entries) { if (entry.respondsTo() != null && !seen.contains(entry.respondsTo())) issues.add("Discussion response must reference an earlier entry: " + entry.id()); seen.add(entry.id()); } }); check(issues, () -> { var all = decisions.list(root, id); var byId = new HashMap(); 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()); 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 net.intrepid.aiengineering.legacyimport.DiscussionImportService().receipts(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); } private void orphans(List issues, Path folder, String directory, List expected) { for (Path entry : Filespace.children(Filespace.resolve(folder, directory))) { Filespace.resolve(folder, folder.relativize(entry).toString()); if (!expected.contains(entry.getFileName().toString())) issues.add("Unreferenced protocol file: " + directory + "/" + entry.getFileName()); } } /** 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 executionPending(Path root, String id) { var issues = new ArrayList(); 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(); 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 mappings, List 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 mappings, List 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(); 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(); var seen = new HashSet(); 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 nextActions) {} public record ProjectStatus(int schemaVersion, ProjectConfig.Identity project, boolean onboarded, List works, CompatibilityService.Summary compatibility) {} /** Read-only projection for human listings; the full JSON contracts remain unchanged. */ public record Overview(Work work, String steps, ValidationReport validation, List nextActions) {} public List overview(Path root, List selected) { return selected.stream().map(w -> { var validation = work(root, w.id()); String progress = "unavailable"; try { var steps = plans.list(root, w.id()).stream().flatMap(p -> p.steps().stream()).toList(); progress = steps.stream().filter(s -> s.status() == Plan.Status.COMPLETED).count() + "/" + steps.size(); } catch (ProtocolException failure) { if (validation.valid()) throw failure; // Keep repairable Works visible without claiming a zero-step plan. } return new Overview(w, progress, validation, actions(root, w, validation)); }).toList(); } 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(), new CompatibilityService().inspect(root).summary()); } public List nextActions(Path root, String id) { var result = new ArrayList(); 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 actions(Path root, Work work) { return actions(root, work, work(root, work.id())); } private List actions(Path root, Work work, ValidationReport validation) { String id = work.id(); var actions = new ArrayList(); 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, "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")); 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 discussionHistory, List decisions, List outstandingQuestions, List artifacts, List plans, String protocolGuide, List topics, List surveys, List dispositions, List 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 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 outstanding(List history) { var answered = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.RESPONSE || e.kind() == DiscussionEntry.Kind.CONCLUSION) .map(DiscussionEntry::respondsTo).filter(Objects::nonNull).toList(); 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(); } public String markdown(Context context) { var w = context.work(); var result = new StringBuilder("# " + w.id() + " — " + w.title() + "\n\nProtocol schema: 1\n\nStatus: " + w.status() + "\n"); section(result, "Goal", w.goal()); section(result, "Description", w.description()); section(result, "Motivation", w.motivation()); section(result, "Constraints", items(w.constraints())); section(result, "Acceptance criteria", items(w.acceptanceCriteria())); section(result, "Repository revisions at Work creation", yaml(w.repositories())); section(result, "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 entries) { if (entries.isEmpty()) return "None recorded."; var out = new StringBuilder(); for (var entry : entries) { if (!out.isEmpty()) out.append('\n'); out.append("### ").append(entry.id()).append(" — ").append(entry.kind()).append("\n\n") .append("Author: ").append(entry.author()).append("\n\nThread: ").append(entry.discussionId()) .append("\n\nCreated: ").append(entry.createdAt()).append('\n'); if (entry.respondsTo() != null) out.append("\nResponds to: ").append(entry.respondsTo()).append('\n'); out.append('\n').append(entry.text()).append('\n'); } return out.toString(); } 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 decisions) { if (decisions.isEmpty()) return "None recorded."; var out = new StringBuilder(); for (var decision : decisions) { if (!out.isEmpty()) out.append('\n'); out.append("### ").append(decision.id()).append(" — ").append(decision.title()).append("\n\n") .append("Approval: ").append(decision.approvalStatus()).append("\n\nAuthor: ").append(decision.author()) .append("\n\nCreated: ").append(decision.createdAt()).append('\n'); subsection(out, "Context", decision.context()); subsection(out, "Approach", decision.approach()); subsection(out, "Alternatives", items(decision.alternatives())); subsection(out, "Rationale", decision.rationale()); subsection(out, "Risks", items(decision.risks())); subsection(out, "Acceptance criteria", items(decision.acceptanceCriteria())); subsection(out, "Evidence", items(decision.evidence())); 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(); } private static void subsection(StringBuilder out, String title, String text) { out.append("\n#### ").append(title).append("\n\n").append(text.isBlank() ? "None recorded." : text).append('\n'); } private static String items(List values) { return values.isEmpty() ? "None recorded." : String.join("\n", values.stream().map(v -> "- " + v).toList()); } private static String yaml(Object value) { if (value instanceof List list && list.isEmpty()) return "None recorded."; return "```yaml\n" + Documents.yaml(value) + "```"; } private static void section(StringBuilder out, String title, String body) { out.append("\n## ").append(title).append("\n\n").append(body.isBlank() ? "None recorded." : body).append('\n'); } }