package net.intrepid.aiengineering.planning; import net.intrepid.aiengineering.filesystem.*; import net.intrepid.aiengineering.work.*; import net.intrepid.aiengineering.decision.*; import net.intrepid.aiengineering.artifact.ArtifactService; import java.nio.file.*; import java.time.Instant; import java.util.*; import java.util.function.Function; 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"); } public List 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; }).toList(); } private void identity(Plan plan, String work, String id) { if (!plan.id().equals(id) || !plan.workId().equals(work)) throw ProtocolException.validation("Plan identity mismatch: " + id); } public Plan get(Path root, String work, String id) { Work.identifier(id, "PLN"); return list(root, work).stream().filter(plan -> plan.id().equals(id)).findFirst() .orElseThrow(() -> ProtocolException.missing("Plan not found: " + id)); } private List chain(Path root, Plan current) { var history = new ArrayList(); 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); 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); history.add(prior); next = prior; } Collections.reverse(history); return List.copyOf(history); } public List history(Path root, String work, String id) { return chain(root, get(root, work, id)); } private void accepted(Path root, String work, List ids) { authority(root, work, ids, false); for (String id : ids) if (decisions.get(root, work, id).approvalStatus() != Decision.Status.ACCEPTED) throw ProtocolException.invalid("Plan execution requires an accepted decision: " + id); } public void requireExecutionAuthority(Path root, String work, List ids) { accepted(root, work, ids); } private void authority(Path root, String work, List ids, boolean creating) { var guidance = works.load(root, work).guidance(); if (guidance == null) return; // Historical Work; adoption is explicit, never a migration on read. guidance.requireMode(); if (ids.isEmpty() && (!guidance.waived() || guidance.mode() == WorkGuidance.Mode.EXPLORATORY)) throw ProtocolException.invalid("A DEC under applicable human authority is required before creating or executing this Plan"); for (String id : ids) { var decision = decisions.get(root, work, id); if (decision.approvalStatus() == Decision.Status.DRAFT && creating) { guidance.requireDecisionRequest(id); if (!guidance.waived()) throw ProtocolException.invalid("Human approval is required for " + id + "; creating a Plan cannot bypass it"); } else if (decision.approvalStatus() == Decision.Status.ACCEPTED && !guidance.waived() && !decision.approvals().getLast().humanApproved()) throw ProtocolException.invalid("Current Work policy requires human approval for " + id + "; system promotion is not human approval"); } } public Plan create(Path root, String workId, String title, String description, List refs, String author) { return Filespace.locked(root, () -> { var work = works.editable(root, workId); String id = works.nextReference(work.plans(), "PLN"), now = Instant.now().toString(); authority(root, workId, refs, true); if (work.guidance() != null && new net.intrepid.aiengineering.discussion.DiscussionService().hasPending(root, workId)) 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 (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 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); 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")); works.touched(root, work, changed.updatedAt()); return changed; }); } public Plan update(Path root, String work, String id, String title, String description, List refs, String by, String reason) { if (title == null && description == null && refs == null) throw ProtocolException.invalid("Specify a plan field to update"); return mutate(root, work, id, by, reason, old -> { old.requireEditable(); if (refs != null) accepted(root, work, refs); if (refs != null) for (var experiment : old.experiments()) { String concern = experiment.questionsDecision(); if (concern != null && old.decisions().contains(concern) && !refs.contains(concern) && refs.stream().noneMatch(candidate -> replaces(root, work, candidate, concern))) throw ProtocolException.invalid("Replace questioned DEC " + concern + " with its accepted revision; dropping the reference does not resolve evidence"); } return old.content(title == null ? old.title() : title, description == null ? old.description() : description, refs == null ? old.decisions() : refs, old.steps(), old.status()); }); } private boolean replaces(Path root, String work, String candidate, String original) { var seen = new HashSet(); for (String current = candidate; current != null && seen.add(current); current = decisions.get(root, work, current).revises()) if (current.equals(original)) return true; return false; } public Plan status(Path root, String work, String id, Plan.Status status, String by, String reason) { ProtocolException.text(by, "plan actor"); ProtocolException.text(reason, "plan change reason"); var current = get(root, work, id); if (current.status() == status) return current; return mutate(root, work, id, by, reason, old -> { // Reopening permits repairing stale references; starting steps still requires current authority. if (status == Plan.Status.ACTIVE && !old.terminal()) accepted(root, work, old.decisions()); if (status == Plan.Status.COMPLETED) { accepted(root, work, old.decisions()); if (!old.completionIssues().isEmpty()) throw ProtocolException.validation(String.join("; ", old.completionIssues())); new ArtifactService().validate(root, work); } return old.content(old.title(), old.description(), old.decisions(), old.steps(), status); }); } /** Scope review retains the cancelled record and its revision chain. */ public Plan exclude(Path root, String work, String id, String step, String by, String reason) { return mutate(root, work, id, by, reason, old -> old.exclude(step == null ? "PLAN" : step, by, reason)); } /** Invoked by the coordination API; Planning never depends on Verification. */ public Plan consolidate(Path root, String work, String id) { var plan = get(root, work, id); if (plan.status() != Plan.Status.OPEN && plan.status() != Plan.Status.ACTIVE) return plan; if (!plan.completionIssues().isEmpty()) return plan; var history = history(root, work, id); for (int i = history.size() - 1; i > 0; i--) { if (history.get(i - 1).terminal() && history.get(i).status() == Plan.Status.ACTIVE) { Instant reopened = Instant.parse(history.get(i).updatedAt()); if (plan.steps().stream().noneMatch(s -> Instant.parse(s.updatedAt()).isAfter(reopened))) return plan; break; } } return status(root, work, id, Plan.Status.COMPLETED, "system:plans", "All required steps completed; reviewed cancellations retained"); } public Plan addStep(Path root, String work, String id, String title, String description, List criteria, List deps, String by, String reason) { return mutate(root, work, id, by, reason, old -> { old.requireEditable(); String stepId = works.nextReference(old.steps().stream().map(Plan.Step::id).toList(), "TSK"); var steps = new ArrayList<>(old.steps()); steps.add(new Plan.Step(stepId, title, description, criteria, deps, Plan.Status.OPEN, "", List.of(), Instant.now().toString())); return old.content(old.title(), old.description(), old.decisions(), steps, old.status()); }); } private Plan.Step step(Plan plan, String id) { Work.identifier(id, "TSK"); return plan.steps().stream().filter(step -> step.id().equals(id)).findFirst() .orElseThrow(() -> ProtocolException.missing("Plan step not found: " + id)); } public Plan updateStep(Path root, String work, String id, String stepId, String title, String description, List criteria, List deps, String by, String reason) { if (title == null && description == null && criteria == null && deps == null) throw ProtocolException.invalid("Specify a step field to update"); return mutate(root, work, id, by, reason, old -> { old.requireEditable(); var previous = step(old, stepId); if (previous.status() == Plan.Status.COMPLETED || previous.status() == Plan.Status.CANCELLED) throw ProtocolException.invalid("Reopen the step before editing its scope"); var changed = new Plan.Step(stepId, title == null ? previous.title() : title, description == null ? previous.description() : description, criteria == null ? previous.acceptanceCriteria() : criteria, deps == null ? previous.dependsOn() : deps, previous.status(), previous.result(), previous.evidence(), Instant.now().toString()); var steps = old.steps().stream().map(step -> step.id().equals(stepId) ? changed : step).toList(); return old.content(old.title(), old.description(), old.decisions(), steps, old.status()); }); } public Plan stepStatus(Path root, String work, String id, String stepId, Plan.Status target, String by, String reason, List evidence) { return mutate(root, work, id, by, reason, old -> { old.requireEditable(); var previous = step(old, stepId); if (target == Plan.Status.ACTIVE || target == Plan.Status.COMPLETED) { 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); 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(); return old.content(old.title(), old.description(), old.decisions(), steps, status); }); } public Plan startExperiment(Path root, String work, String id, String stepId, String hypothesis, String criterion, String invocation, String retry, String reconsideration, String by, String reason) { return mutate(root, work, id, by, reason, old -> { old.requireEditable(); accepted(root, work, old.decisions()); ProtocolException.text(hypothesis, "experiment hypothesis"); if (works.load(root, work).guidance() == null) throw ProtocolException.invalid("Adopt Work guidance before recording Plan experiments"); if (stepId != null) step(old, stepId); for (var prior : old.experiments()) if (prior.failed() && Experiment.normalized(prior.hypothesis()).equals(Experiment.normalized(hypothesis)) && (retry == null || reconsideration == null || reconsideration.isBlank())) throw ProtocolException.invalid("Reconsider the failed hypothesis with --retry-of and --reconsideration before repeating it"); var experiment = new Experiment(works.nextReference(old.experiments().stream().map(Experiment::id).toList(), "EXP"), stepId, hypothesis, criterion, invocation, retry, reconsideration, by, Instant.now().toString(), Experiment.Outcome.OPEN, null, null, null, List.of(), null, null, null); var all = new ArrayList<>(old.experiments()); all.add(experiment); return old.withExperiments(all); }); } public Plan finishExperiment(Path root, String work, String id, String experimentId, Experiment.Outcome outcome, String observation, String interpretation, String nextAction, List evidence, String concern, String by, String reason) { return mutate(root, work, id, by, reason, old -> { old.requireEditable(); var experiment = old.experiments().stream().filter(e -> e.id().equals(experimentId)).findFirst() .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); 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()); }); } }