feat: add Work guidance and adaptive Plan experiments
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/AI Engineering/pipeline/head There was a failure building this commit
build / jvm (push) Canceled after 0s
build / native (macos-15, macos-arm64) (push) Canceled after 0s
build / native (ubuntu-24.04, linux-x86_64) (push) Canceled after 0s
build / native (windows-2025, windows-x86_64) (push) Canceled after 0s

Persist explicit human discussion choices, DEC requests and approval policies. Add optional evidence-backed Plan experiments and align context, adapters and next actions under protocol contract 3.

Include WRK-000B decisions, plan history and verification evidence: 167 JVM tests, 25 focused checks, Jenkins fixtures and native smoke coverage.
This commit is contained in:
2026-11-16 17:33:24 +00:00
parent 3c75ce70f6
commit f5d5db73c2
104 changed files with 4432 additions and 106 deletions
@@ -17,6 +17,10 @@ public final class NativeHints implements RuntimeHintsRegistrar {
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, Decision.ApprovalOrigin.class, Plan.class, Plan.Step.class, Plan.Exclusion.class,
net.intrepid.aiengineering.work.WorkGuidance.class, net.intrepid.aiengineering.work.WorkGuidance.Choice.class,
net.intrepid.aiengineering.work.WorkGuidance.Request.class, net.intrepid.aiengineering.work.WorkGuidance.Mode.class,
net.intrepid.aiengineering.work.WorkGuidance.ApprovalPolicy.class, net.intrepid.aiengineering.planning.Experiment.class,
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,
Work.Event.class, Work.Completion.class, Work.CriterionResult.class, Work.Integration.class,
@@ -63,6 +63,7 @@ public final class AgentService {
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());
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());
data.put("entries",context.entries()); data.put("topics",context.topics()); data.put("surveys",context.surveys());
@@ -133,6 +134,7 @@ public final class AgentService {
new DispositionService().check(root,context.work().id(),d.entry(),d.action(),d.evidence());
}
if(output.decision()!=null) {
if (context.work().guidance() != null) context.work().guidance().requireDecisionRequest(works.nextReference(context.work().decisions(), "DEC"));
var d=output.decision(); text(d.title(),"decision title"); text(d.context(),"decision context"); text(d.approach(),"decision approach"); text(d.rationale(),"decision rationale");
if(!context.work().artifacts().containsAll(d.evidence())) throw ProtocolException.invalid("Unknown proposed decision evidence");
}
@@ -139,6 +139,8 @@ public final class CliAgentAdapter implements AgentAdapter {
+ "Previous RUN summaries are derived interpretations, not verified observations; prefer canonical Discussion/evidence. "
+ "For summarize: retain source IDs/pending issues in summary and normally leave proposal arrays empty. For clarify: propose a survey with suggestions. "
+ "For refine/analyze: propose proportional topics, surveys or entries; keep formal decisions as drafts requiring review.\n" + Documents.json(payload);
if (context.work().guidance() != null) prompt = "Applicable AIE Work conduct: " + context.work().guidance().instructions()
+ " If mode is unspecified, ask for it using a survey and do not emit a decision. In EXPLORATORY mode, emit a formal decision only when decisionRequests authorizes the next DEC; otherwise propose a synthesis and suggest requesting a DEC.\n" + prompt;
var reply = invoke(request.executor(), "proposal", prompt);
var proposal = Documents.parseJson(reply.json(), WireProposal.class).canonical(id);
if (request.activity().equals("clarify") && proposal.surveys().isEmpty()) throw ProtocolException.validation("Clarification requires a survey with suggestions");
@@ -39,7 +39,7 @@ public final class EngineeringCli implements Runnable {
.addSubcommand("project", new ProjectCommands()).addSubcommand("repo", new RepoCommands())
.addSubcommand("work", new WorkCommands()).addSubcommand("discussion", new DiscussionCommands())
.addSubcommand("decision", new DecisionCommands()).addSubcommand("artifact", new ArtifactCommands())
.addSubcommand("plan", new CommandLine(new PlanCommands()).addSubcommand("step", new StepCommands()))
.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());
commandLine.addSubcommand("import", new CommandLine(new ImportCommands()).addSubcommand("discussion", new DiscussionImportCommand()));
@@ -213,6 +213,27 @@ public final class EngineeringCli implements Runnable {
}
@Command(name = "work", mixinStandardHelpOptions = true, description = "Create, inspect, validate and export Works.")
public class WorkCommands {
@Command(name = "guidance", mixinStandardHelpOptions = true, description = "Show or record explicit human discussion mode and Work-wide DEC approval policy; choices are never inferred.")
int guidance(@Parameters(index = "0") String id,
@Option(names = "--mode") WorkGuidance.Mode mode,
@Option(names = "--approval") WorkGuidance.ApprovalPolicy policy,
@Option(names = "--by") String by, @Option(names = "--reason") String reason,
@Option(names = "--human-approved") boolean humanApproved,
@Option(names = "--format", defaultValue = "markdown") Format format) {
if (mode == null && policy == null) {
if (by != null || reason != null || humanApproved) throw ProtocolException.invalid("Specify --mode or --approval to record a human choice");
return emit(works.load(root(), id).guidance(), format);
}
return change(id, by, () -> works.guidance(root(), id, mode, policy, by, reason, humanApproved), format);
}
@Command(name = "request-decision", mixinStandardHelpOptions = true, description = "Record the human's request for the next DEC; exploratory discussion cannot end itself.")
int requestDecision(@Parameters(index = "0") String id,
@Option(names = "--decision", description = "Explicit existing DEC, for example when a direct discussion becomes exploratory; default is the next DEC.") String decision,
@Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason,
@Option(names = "--human-approved", required = true) boolean humanApproved,
@Option(names = "--format", defaultValue = "markdown") Format format) {
return change(id, by, () -> works.requestDecision(root(), id, decision, by, reason, humanApproved), format);
}
@Command(name = "reconcile", mixinStandardHelpOptions = true, description = "Consolidate Plans and recover missed completion/EPIC propagation; no model is invoked.")
int reconcile(@Parameters(index = "0") String id,
@Option(names = "--requester", defaultValue = "human") String requester,
@@ -228,8 +249,14 @@ public final class EngineeringCli implements Runnable {
@Option(names = "--constraint") List<String> constraints,
@Option(names = "--acceptance") List<String> criteria,
@Option(names = "--repo") List<String> repositories,
@Option(names = "--author", defaultValue = "human") String author) {
return emit(works.create(root(), title, description, goal, motivation, safe(constraints), safe(criteria), safe(repositories), author), Format.markdown);
@Option(names = "--author", defaultValue = "human") String author,
@Option(names = "--mode", description = "Human choice of DIRECT or EXPLORATORY; no default is inferred.") WorkGuidance.Mode mode,
@Option(names = "--approval", description = "Human instruction: REQUIRED or WAIVED for this Work only.") WorkGuidance.ApprovalPolicy policy,
@Option(names = "--choice-reason") String choiceReason, @Option(names = "--human-approved") boolean humanApproved) {
WorkGuidance initial = null;
if (mode != null || policy != null) initial = WorkGuidance.pending().choose(mode, policy, author, choiceReason, humanApproved);
else if (choiceReason != null || humanApproved) throw ProtocolException.invalid("Specify --mode or --approval for a human choice");
return emit(works.create(root(), title, description, goal, motivation, safe(constraints), safe(criteria), safe(repositories), author, initial), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Option(names = "--open", description = "Only nonterminal, unarchived Works (OPEN, ACTIVE, BLOCKED).") boolean open,
@@ -394,9 +421,38 @@ public final class EngineeringCli implements Runnable {
return emit(new DecisionService().revise(root(), work, id, by, reason), Format.markdown);
}
}
@Command(name = "experiment", mixinStandardHelpOptions = true, description = "Optional experiments; criteria precede observations, and execution is external.")
public class ExperimentCommands {
@Command(name = "start", mixinStandardHelpOptions = true)
int start(@Parameters(index = "0") String work, @Parameters(index = "1") String plan,
@Option(names = "--step") String step, @Option(names = "--hypothesis", required = true) String hypothesis,
@Option(names = "--criterion", required = true) String criterion, @Option(names = "--invocation", required = true) String invocation,
@Option(names = "--retry-of") String retry, @Option(names = "--reconsideration") String reconsideration,
@Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) {
return change(work, by, () -> new PlanService().startExperiment(root(), work, plan, step, hypothesis, criterion,
invocation, retry, reconsideration, by, reason), Format.markdown);
}
@Command(name = "finish", mixinStandardHelpOptions = true)
int finish(@Parameters(index = "0") String work, @Parameters(index = "1") String plan, @Parameters(index = "2") String experiment,
@Option(names = "--outcome", required = true) Experiment.Outcome outcome,
@Option(names = "--observation", required = true) String observation,
@Option(names = "--interpretation", required = true) String interpretation,
@Option(names = "--next-action", required = true) String nextAction,
@Option(names = "--evidence", required = true) List<String> evidence,
@Option(names = "--questions-decision") String concern,
@Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) {
return change(work, by, () -> new PlanService().finishExperiment(root(), work, plan, experiment, outcome,
observation, interpretation, nextAction, evidence, concern, by, reason), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Parameters(index = "0") String work, @Parameters(index = "1") String plan,
@Option(names = "--format", defaultValue = "markdown") Format format) {
return emit(new PlanService().get(root(), work, plan).experiments(), format);
}
}
@Command(name = "plan", mixinStandardHelpOptions = true, description = "Maintain proportional implementation plans; execution remains external.")
public class PlanCommands {
@Command(name = "create", mixinStandardHelpOptions = true, description = "Create a Plan and automatically promote referenced draft decisions without a model call.")
@Command(name = "create", mixinStandardHelpOptions = true, description = "Create a Plan respecting Work authority; draft promotion requires an explicit Work-wide waiver in guided Works.")
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) {
@@ -42,6 +42,7 @@ public final class DecisionService {
public Decision draft(Path root, String workId, String title, String context, String approach, String rationale, List<String> evidence, String author, String text) {
return Filespace.locked(root, () -> {
var work = works.editable(root, workId); evidence(work, evidence); String id = works.nextReference(work.decisions(), "DEC"); String now = Instant.now().toString();
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;
@@ -113,6 +114,10 @@ public final class DecisionService {
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());
if (work.guidance() != null) {
work.guidance().requireDecisionRequest(old.id());
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);
proposed.put(old.id(), old.acceptForPlan(plan, requester, Revisions.hash(original)));
@@ -153,6 +158,7 @@ public final class DecisionService {
if (old.approvalStatus() != Decision.Status.ACCEPTED && old.approvalStatus() != Decision.Status.REJECTED)
throw ProtocolException.invalid("Revise the current accepted/rejected decision; use update for a draft");
String next = works.nextReference(work.decisions(), "DEC"), now = Instant.now().toString();
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;
@@ -7,6 +7,13 @@ import java.time.Instant;
import java.util.List;
public final class DiscussionService {
public boolean hasPending(Path root, String work) {
var entries = list(root, work);
var answered = entries.stream().filter(e -> e.kind() == DiscussionEntry.Kind.RESPONSE || e.kind() == DiscussionEntry.Kind.CONCLUSION)
.map(DiscussionEntry::respondsTo).filter(java.util.Objects::nonNull).toList();
return entries.stream().anyMatch(e -> (e.kind() == DiscussionEntry.Kind.QUESTION || e.kind() == DiscussionEntry.Kind.ISSUE) && !answered.contains(e.id()))
|| new SurveyService().list(root, work).stream().anyMatch(s -> s.questions().isEmpty() || !s.pending().isEmpty());
}
private final WorkService works = new WorkService();
public List<DiscussionEntry> list(Path root, String id) {
Work work = works.load(root, id); Path folder = works.folder(root, id);
@@ -0,0 +1,41 @@
package net.intrepid.aiengineering.planning;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.work.Work;
import java.time.Instant;
import java.util.*;
/** An optional evidence-producing attempt, not a mandatory OODA phase or an executor. */
public record Experiment(String id, String stepId, String hypothesis, String successCriterion, String invocation,
String retryOf, String reconsideration, String by, String createdAt, Outcome outcome,
String observation, String interpretation, String nextAction, List<String> evidence, String questionsDecision,
String finishedAt, String finishedBy) {
public enum Outcome { OPEN, CONFIRMED, REFUTED, INCONCLUSIVE }
public Experiment {
Work.identifier(id, "EXP"); if (stepId != null) Work.identifier(stepId, "TSK");
ProtocolException.text(hypothesis, "experiment hypothesis"); ProtocolException.text(successCriterion, "experiment success criterion");
ProtocolException.text(invocation, "experiment invocation"); ProtocolException.text(by, "experiment author"); Instant.parse(createdAt);
Objects.requireNonNull(outcome); evidence = List.copyOf(evidence); evidence.forEach(e -> Work.identifier(e, "ART"));
if (evidence.stream().distinct().count() != evidence.size()) throw ProtocolException.validation("Duplicate experiment evidence");
if (retryOf != null) { Work.identifier(retryOf, "EXP"); ProtocolException.text(reconsideration, "reconsidered hypothesis or new evidence"); }
else if (reconsideration != null) throw ProtocolException.invalid("Reconsideration requires --retry-of");
if (questionsDecision != null) Work.identifier(questionsDecision, "DEC");
if (outcome == Outcome.OPEN) {
if (observation != null || interpretation != null || nextAction != null || !evidence.isEmpty()
|| questionsDecision != null || finishedAt != null || finishedBy != null)
throw ProtocolException.validation("Open experiments cannot claim observed results");
} else {
ProtocolException.text(observation, "experiment observation"); ProtocolException.text(interpretation, "experiment interpretation");
ProtocolException.text(nextAction, "experiment next action"); ProtocolException.text(finishedBy, "experiment result actor");
if (evidence.isEmpty()) throw ProtocolException.validation("Experiment results require owned evidence");
if (Instant.parse(finishedAt).isBefore(Instant.parse(createdAt))) throw ProtocolException.validation("Result precedes experiment criteria");
}
}
public Experiment finish(Outcome result, String observed, String interpreted, String next, List<String> refs, String concern, String actor) {
if (outcome != Outcome.OPEN || result == Outcome.OPEN) throw ProtocolException.invalid("Finish an open experiment with an observed outcome; results are immutable");
return new Experiment(id, stepId, hypothesis, successCriterion, invocation, retryOf, reconsideration, by, createdAt,
result, observed, interpreted, next, refs, concern, Instant.now().toString(), actor);
}
public boolean failed() { return outcome == Outcome.REFUTED || outcome == Outcome.INCONCLUSIVE; }
public static String normalized(String hypothesis) { return hypothesis.strip().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT); }
}
@@ -11,7 +11,14 @@ import net.intrepid.aiengineering.filesystem.Revisions;
public record Plan(int schemaVersion, String id, String workId, String title, String description,
List<String> decisions, List<Step> steps, Status status, String author, String createdAt,
int revision, String previousHash, String updatedAt, String updatedBy, String changeReason,
@JsonInclude(JsonInclude.Include.NON_NULL) List<Exclusion> exclusions) {
@JsonInclude(JsonInclude.Include.NON_NULL) List<Exclusion> exclusions,
@JsonInclude(JsonInclude.Include.NON_EMPTY) List<Experiment> experiments) {
public Plan(int schemaVersion, String id, String workId, String title, String description,
List<String> decisions, List<Step> steps, Status status, String author, String createdAt,
int revision, String previousHash, String updatedAt, String updatedBy, String changeReason, List<Exclusion> exclusions) {
this(schemaVersion, id, workId, title, description, decisions, steps, status, author, createdAt,
revision, previousHash, updatedAt, updatedBy, changeReason, exclusions, List.of());
}
public Plan(int schemaVersion, String id, String workId, String title, String description,
List<String> decisions, List<Step> steps, Status status, String author, String createdAt,
int revision, String previousHash, String updatedAt, String updatedBy, String changeReason) {
@@ -40,6 +47,7 @@ public record Plan(int schemaVersion, String id, String workId, String title, St
}
}
public Plan {
experiments = experiments == null ? List.of() : List.copyOf(experiments);
exclusions = exclusions == null ? null : List.copyOf(exclusions);
ProtocolException.schema(schemaVersion); Work.identifier(id, "PLN"); Work.identifier(workId, "WRK");
ProtocolException.text(title, "plan title"); Objects.requireNonNull(description); ProtocolException.text(author, "plan author");
@@ -59,6 +67,18 @@ public record Plan(int schemaVersion, String id, String workId, String title, St
}
var visited = new HashSet<String>();
for (var step : steps) visit(step.id(), byId, new HashSet<>(), visited);
var previousExperiments = new HashMap<String, Experiment>();
for (var experiment : experiments) {
if (experiment.stepId() != null && !byId.containsKey(experiment.stepId())) throw ProtocolException.validation("Unknown experiment step");
if (experiment.retryOf() != null) {
var prior = previousExperiments.get(experiment.retryOf());
if (prior == null || !prior.failed()) throw ProtocolException.validation("Retry must reference an earlier refuted or inconclusive experiment");
}
if (previousExperiments.putIfAbsent(experiment.id(), experiment) != null) throw ProtocolException.validation("Duplicate experiment ID");
if (status == Status.COMPLETED && (experiment.outcome() == Experiment.Outcome.OPEN
|| (experiment.questionsDecision() != null && decisions.contains(experiment.questionsDecision()))))
throw ProtocolException.validation("Resolve experiment and decision concerns before Plan completion");
}
if (status == Status.COMPLETED && (steps.isEmpty() || steps.stream().anyMatch(step -> step.status() != Status.COMPLETED && step.status() != Status.CANCELLED)))
throw ProtocolException.validation("Complete or cancel all plan steps before completion");
}
@@ -70,14 +90,28 @@ public record Plan(int schemaVersion, String id, String workId, String title, St
}
public Plan content(String nextTitle, String nextDescription, List<String> refs, List<Step> nextSteps, Status nextStatus) {
return new Plan(schemaVersion, id, workId, nextTitle, nextDescription, refs, nextSteps, nextStatus, author, createdAt,
revision, previousHash, updatedAt, updatedBy, changeReason, exclusions);
revision, previousHash, updatedAt, updatedBy, changeReason, exclusions, experiments);
}
public Plan snapshot(String by, String reason, String hash) {
return new Plan(schemaVersion, id, workId, title, description, decisions, steps, status, author, createdAt,
revision + 1, hash, Instant.now().toString(), by, reason, exclusions);
revision + 1, hash, Instant.now().toString(), by, reason, exclusions, experiments);
}
public Plan withExperiments(List<Experiment> value) {
return new Plan(schemaVersion, id, workId, title, description, decisions, steps, status, author, createdAt,
revision, previousHash, updatedAt, updatedBy, changeReason, exclusions, value);
}
public boolean experimentBlocks(Experiment experiment, String step) {
if (experiment.outcome() != Experiment.Outcome.OPEN && (experiment.questionsDecision() == null || !decisions.contains(experiment.questionsDecision()))) return false;
if (step == null || experiment.stepId() == null || step.equals(experiment.stepId())) return true;
return steps.stream().filter(s -> s.id().equals(step)).findFirst().orElseThrow().dependsOn().stream().anyMatch(d -> experimentBlocks(experiment, d));
}
public void requireExperimentReady(String step) {
for (var experiment : experiments) if (experimentBlocks(experiment, step))
throw ProtocolException.invalid("Investigate " + experiment.id() + " and review its DEC concern before executing affected work");
}
public String exclusionScope(String target) {
Object input = target.equals("PLAN") ? List.of(id, title, description, decisions, steps, status)
Object input = target.equals("PLAN") ? (experiments.isEmpty() ? List.of(id, title, description, decisions, steps, status)
: List.of(id, title, description, decisions, steps, status, experiments))
: steps.stream().filter(s -> s.id().equals(target)).findFirst().orElseThrow(() -> ProtocolException.invalid("Unknown step: " + target));
return Revisions.hash(Documents.json(input));
}
@@ -94,12 +128,17 @@ public record Plan(int schemaVersion, String id, String workId, String title, St
var reviews = new ArrayList<>(exclusions == null ? List.<Exclusion>of() : exclusions);
reviews.add(new Exclusion(target, exclusionScope(target), by, reason, Instant.now().toString()));
return new Plan(schemaVersion, id, workId, title, description, decisions, steps, status, author, createdAt,
revision, previousHash, updatedAt, updatedBy, changeReason, reviews);
revision, previousHash, updatedAt, updatedBy, changeReason, reviews, experiments);
}
public List<String> completionIssues() {
var issues = new ArrayList<String>();
if (steps.isEmpty()) issues.add("No steps: " + id);
if (steps.stream().noneMatch(s -> s.status() == Status.COMPLETED)) issues.add("No completed steps: " + id);
for (var experiment : experiments) {
if (experiment.outcome() == Experiment.Outcome.OPEN) issues.add("Observe experiment " + id + "/" + experiment.id());
if (experiment.questionsDecision() != null && decisions.contains(experiment.questionsDecision()))
issues.add("Review questioned decision " + experiment.questionsDecision() + " from " + experiment.id());
}
for (var step : steps) if (step.status() != Status.COMPLETED && !excluded(step.id()))
issues.add(id + "/" + step.id() + " is " + step.status() + (step.status() == Status.CANCELLED ? "; review cancelled scope explicitly" : ""));
return List.copyOf(issues);
@@ -39,12 +39,33 @@ public final class PlanService {
}
public List<Plan> history(Path root, String work, String id) { return chain(root, get(root, work, id)); }
private void accepted(Path root, String work, List<String> 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<String> ids) { accepted(root, work, ids); }
private void authority(Path root, String work, List<String> 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<String> 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);
@@ -85,15 +106,29 @@ public final class PlanService {
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<String>();
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()));
@@ -146,7 +181,9 @@ public final class PlanService {
public Plan stepStatus(Path root, String work, String id, String stepId, Plan.Status target, String by, String reason, List<String> 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());
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());
@@ -155,4 +192,33 @@ public final class PlanService {
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<String> 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());
});
}
}
@@ -1,2 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work", "decision", "artifact"})
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work", "decision", "artifact", "discussion"})
package net.intrepid.aiengineering.planning;
@@ -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 = 2;
public static final List<Integer> READABLE = List.of(1, 2);
public static final int CURRENT = 3;
public static final List<Integer> READABLE = List.of(1, 2, 3);
/** 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) {
@@ -15,6 +15,7 @@ public final class ProtocolGuide {
+ "`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"
+ "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() {}
public static String bundled(String name) {
@@ -49,6 +50,8 @@ public final class ProtocolGuide {
|| !"explicit-attestation".equals(humanApproval) || !"external-human-or-agent".equals(execution)
|| (legacyImport && (ProtocolContract.effective(protocolVersion) < 2 || capabilities == null || !capabilities.contains("discussion-import"))))
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");
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");
@@ -36,7 +36,7 @@ public final class CompatibilityService {
new RecordType("surveys", Survey.class, "description"), new RecordType("dispositions", Disposition.class, "reason"),
new RecordType("agent-runs", AgentRun.class, "task"), new RecordType("epic", Epic.class, "reason"));
private static final List<String> WORK_DEFAULTS = List.of("plans", "completions", "events", "archived",
"topics", "surveys", "dispositions", "agentRuns", "epic");
"topics", "surveys", "dispositions", "agentRuns", "epic", "guidance");
public Report inspect(Path root) {
var findings = new ArrayList<Finding>();
@@ -89,6 +89,10 @@ public final class VerificationService {
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());
for (var experiment : plan.experiments()) {
if (!work.artifacts().containsAll(experiment.evidence())) issues.add("Missing experiment evidence: " + experiment.id());
if (experiment.questionsDecision() != null && !work.decisions().contains(experiment.questionsDecision())) issues.add("Missing questioned decision: " + experiment.questionsDecision());
}
}));
check(issues, () -> artifacts.validate(root, id));
check(issues, () -> new net.intrepid.aiengineering.legacyimport.DiscussionImportService().receipts(root, id));
@@ -153,6 +157,7 @@ public final class VerificationService {
var issues = new ArrayList<>(work(root, id).issues());
check(issues, () -> {
Work work = works.load(root, id);
if (work.guidance() != null) check(issues, () -> work.guidance().requireMode());
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");
@@ -168,11 +173,15 @@ 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>();
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");
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);
if (guided != null) for (var plan : plans.list(root, id)) if (!plan.excluded("PLAN"))
check(issues, () -> plans.requireExecutionAuthority(root, id, plan.decisions()));
return List.copyOf(issues);
}
public String scopeHash(Path root, Work work) { return scopeHash(root, work, false); }
@@ -183,6 +192,7 @@ public final class VerificationService {
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());
if (work.guidance() != null) scope.put("guidance", work.guidance());
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 ||
@@ -319,22 +329,60 @@ public final class VerificationService {
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()));
var guidance = work.guidance();
if (guidance != null && guidance.mode() == WorkGuidance.Mode.UNSPECIFIED) {
actions.add(new Action("ASK_DISCUSSION_MODE", id, "Ask the human for DIRECT or EXPLORATORY; never infer the choice", "aie work guidance " + id + " --help"));
return List.copyOf(actions);
}
for (var decision : decisions.list(root, id)) if (decision.approvalStatus() == Decision.Status.DRAFT) {
if (guidance != null && guidance.mode() == WorkGuidance.Mode.EXPLORATORY
&& guidance.decisionRequests().stream().noneMatch(r -> r.decisionId().equals(decision.id())))
actions.add(new Action("CONTINUE_DISCUSSION", id, "The human must end exploration and request " + decision.id(), "aie work request-decision " + id + " --decision " + decision.id() + " --help"));
else actions.add(new Action("REVIEW_DECISION", id, "Review " + decision.id() + (guidance != null && !guidance.waived()
? "; explicit human approval is required before planning" : "; accept explicitly or create a Plan under applicable authority"), "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 (guidance != null) {
try { plans.requireExecutionAuthority(root, id, plan.decisions()); }
catch (ProtocolException missing) { actions.add(new Action("REVIEW_PLAN_AUTHORITY", id, missing.getMessage(), "aie work guidance " + id)); continue; }
}
for (var experiment : plan.experiments()) {
if (experiment.outcome() == Experiment.Outcome.OPEN) actions.add(new Action("OBSERVE_EXPERIMENT", id,
plan.id() + "/" + experiment.id() + ": record observations, evidence, interpretation and next action", "aie plan experiment finish " + id + " " + plan.id() + " " + experiment.id() + " --help"));
if (experiment.questionsDecision() != null && plan.decisions().contains(experiment.questionsDecision())) actions.add(new Action("REVISIT_DECISION", id,
experiment.questionsDecision() + " questioned by " + experiment.id() + "; continue authorized investigation and independent work", "aie work context " + id));
}
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";
if (plan.experiments().stream().anyMatch(e -> plan.experimentBlocks(e, step.id()))) code = "INVESTIGATE_EXPERIMENT";
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))
if (!plan.steps().isEmpty() && plan.completionIssues().isEmpty())
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"));
if (work.plans().isEmpty()) {
if (guidance == null) actions.add(new Action("CREATE_PLAN", id, "Define executable Plans; an empty set cannot auto-complete", "aie plan create " + id + " --help"));
else if (!discussions.hasPending(root, id)) {
var all = decisions.list(root, id);
boolean ready = (all.isEmpty() && guidance.waived() && guidance.mode() == WorkGuidance.Mode.DIRECT)
|| all.stream().anyMatch(d -> (d.approvalStatus() == Decision.Status.ACCEPTED && (guidance.waived() || d.approvals().getLast().humanApproved()))
|| (d.approvalStatus() == Decision.Status.DRAFT && guidance.waived() && (guidance.mode() == WorkGuidance.Mode.DIRECT
|| guidance.decisionRequests().stream().anyMatch(r -> r.decisionId().equals(d.id())))));
if (ready)
actions.add(new Action("CREATE_PLAN", id, "Create a Plan from the DEC under recorded human authority", "aie plan create " + id + " --help"));
else if (all.isEmpty()) {
String next = works.nextReference(work.decisions(), "DEC");
boolean requested = guidance.decisionRequests().stream().anyMatch(r -> r.decisionId().equals(next));
actions.add(new Action(guidance.mode() == WorkGuidance.Mode.EXPLORATORY && !requested ? "CONTINUE_DISCUSSION" : "PREPARE_DECISION", id,
guidance.instructions(), "aie work context " + id));
}
}
}
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));
@@ -343,14 +391,16 @@ 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) {}
ProjectConfig.Agents agents, EpicCoordinator.Evaluation epic, String parentEpic, PlanCoordinator.Evaluation consolidation, String guidanceInstructions) {}
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));
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());
}
private List<String> outstanding(Path root, String id) {
var all = new ArrayList<>(outstanding(discussions.list(root, id)));
@@ -368,6 +418,7 @@ public final class VerificationService {
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, "Work guidance", context.guidanceInstructions() + "\n\n" + (w.guidance() == null ? "Legacy record; no preference inferred." : yaml(w.guidance())));
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()));
@@ -10,7 +10,18 @@ public record Work(int schemaVersion, String id, String title, String descriptio
List<String> constraints, List<String> acceptanceCriteria, Status status, String createdAt, String updatedAt,
String author, List<Revision> repositories, List<String> discussions, List<String> decisions, List<String> artifacts,
List<String> plans, List<Completion> completions, List<Event> events, Boolean archived,
List<String> topics, List<String> surveys, List<String> dispositions, List<String> agentRuns, Boolean epic) {
List<String> topics, List<String> surveys, List<String> dispositions, List<String> agentRuns, Boolean epic,
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) WorkGuidance guidance) {
/** Historical callers and records keep their original semantics and serialized hashes. */
public Work(int schemaVersion, String id, String title, String description, String goal, String motivation,
List<String> constraints, List<String> acceptanceCriteria, Status status, String createdAt, String updatedAt,
String author, List<Revision> repositories, List<String> discussions, List<String> decisions, List<String> artifacts,
List<String> plans, List<Completion> completions, List<Event> events, Boolean archived,
List<String> topics, List<String> surveys, List<String> dispositions, List<String> agentRuns, Boolean epic) {
this(schemaVersion, id, title, description, goal, motivation, constraints, acceptanceCriteria, status, createdAt,
updatedAt, author, repositories, discussions, decisions, artifacts, plans, completions, events, archived,
topics, surveys, dispositions, agentRuns, epic, null);
}
public static final long MAX_NUMBER = 0xFFFFFFFFFL;
public enum Status { OPEN, ACTIVE, BLOCKED, COMPLETED, CANCELLED }
public Work {
@@ -63,7 +74,7 @@ public record Work(int schemaVersion, String id, String title, String descriptio
kind.equals("discussions") ? refs : discussions, kind.equals("decisions") ? refs : decisions,
kind.equals("artifacts") ? refs : artifacts, kind.equals("plans") ? refs : plans, completions, events, archived,
kind.equals("topics") ? refs : topics, kind.equals("surveys") ? refs : surveys,
kind.equals("dispositions") ? refs : dispositions, kind.equals("agentRuns") ? refs : agentRuns, epic);
kind.equals("dispositions") ? refs : dispositions, kind.equals("agentRuns") ? refs : agentRuns, epic, guidance);
}
public Work withStatus(Status value) {
return withStatus(value, "human", "Status set to " + value);
@@ -100,20 +111,26 @@ public record Work(int schemaVersion, String id, String title, String descriptio
if (Objects.equals(title, nextTitle) && Objects.equals(description, nextDescription) && Objects.equals(goal, nextGoal)
&& Objects.equals(motivation, nextMotivation) && constraints.equals(nextConstraints) && acceptanceCriteria.equals(nextCriteria)) return this;
return new Work(schemaVersion, id, nextTitle, nextDescription, nextGoal, nextMotivation, nextConstraints, nextCriteria,
status, createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts, plans, completions, events, archived, topics, surveys, dispositions, agentRuns, epic);
status, createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts, plans, completions, events, archived, topics, surveys, dispositions, agentRuns, epic, guidance);
}
public boolean terminal() { return status == Status.COMPLETED || status == Status.CANCELLED; }
public Work touched(String at) {
requireEditable();
return new Work(schemaVersion, id, title, description, goal, motivation, constraints, acceptanceCriteria, status,
createdAt, at, author, repositories, discussions, decisions, artifacts, plans, completions, events, archived, topics, surveys, dispositions, agentRuns, epic);
createdAt, at, author, repositories, discussions, decisions, artifacts, plans, completions, events, archived, topics, surveys, dispositions, agentRuns, epic, guidance);
}
public Work asEpic() {
requireEditable();
if (epic) return this;
return new Work(schemaVersion, id, title, description, goal, motivation, constraints, acceptanceCriteria, status,
createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts, plans, completions, events, archived,
topics, surveys, dispositions, agentRuns, true);
topics, surveys, dispositions, agentRuns, true, guidance);
}
public Work withGuidance(WorkGuidance value) {
requireEditable();
return new Work(schemaVersion, id, title, description, goal, motivation, constraints, acceptanceCriteria, status,
createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts, plans, completions,
events, archived, topics, surveys, dispositions, agentRuns, epic, value);
}
public void requireEditable() {
if (archived || terminal()) throw ProtocolException.invalid("Reopen " + id + " before modifying its records");
@@ -203,6 +220,6 @@ public record Work(int schemaVersion, String id, String title, String descriptio
private Work evolve(Status value, boolean archive, List<Completion> history, Event event) {
var audit = new java.util.ArrayList<>(events); audit.add(event);
return new Work(schemaVersion, id, title, description, goal, motivation, constraints, acceptanceCriteria, value,
createdAt, event.at(), author, repositories, discussions, decisions, artifacts, plans, history, audit, archive, topics, surveys, dispositions, agentRuns, epic);
createdAt, event.at(), author, repositories, discussions, decisions, artifacts, plans, history, audit, archive, topics, surveys, dispositions, agentRuns, epic, guidance);
}
}
@@ -0,0 +1,65 @@
package net.intrepid.aiengineering.work;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.time.Instant;
import java.util.*;
/** Human choices, independent from Work status and from execution autonomy. */
public record WorkGuidance(Mode mode, ApprovalPolicy approvalPolicy, List<Choice> history, List<Request> decisionRequests) {
public enum Mode { UNSPECIFIED, DIRECT, EXPLORATORY }
public enum ApprovalPolicy { REQUIRED, WAIVED }
public record Choice(Mode mode, ApprovalPolicy approvalPolicy, String by, String reason, String at, boolean humanApproved) {
public Choice { Objects.requireNonNull(mode); Objects.requireNonNull(approvalPolicy); attestation(by, reason, at, humanApproved); }
}
public record Request(String decisionId, String by, String reason, String at, boolean humanApproved) {
public Request { Work.identifier(decisionId, "DEC"); attestation(by, reason, at, humanApproved); }
}
private static void attestation(String by, String reason, String at, boolean approved) {
ProtocolException.text(by, "human choice actor"); ProtocolException.text(reason, "human choice reason"); Instant.parse(at);
if (!approved) throw ProtocolException.invalid("Explicit human instruction requires --human-approved; never infer a choice or waiver");
}
public WorkGuidance {
Objects.requireNonNull(mode); Objects.requireNonNull(approvalPolicy);
history = List.copyOf(history); decisionRequests = List.copyOf(decisionRequests);
if (history.isEmpty()) {
if (mode != Mode.UNSPECIFIED || approvalPolicy != ApprovalPolicy.REQUIRED || !decisionRequests.isEmpty())
throw ProtocolException.validation("Work guidance requires human choice history");
} else if (history.getLast().mode() != mode || history.getLast().approvalPolicy() != approvalPolicy)
throw ProtocolException.validation("Work guidance differs from its latest human choice");
if (decisionRequests.stream().map(Request::decisionId).distinct().count() != decisionRequests.size())
throw ProtocolException.validation("Duplicate human decision requests");
}
public static WorkGuidance pending() { return new WorkGuidance(Mode.UNSPECIFIED, ApprovalPolicy.REQUIRED, List.of(), List.of()); }
public WorkGuidance choose(Mode nextMode, ApprovalPolicy nextPolicy, String by, String reason, boolean humanApproved) {
var choice = new Choice(nextMode == null ? mode : nextMode, nextPolicy == null ? approvalPolicy : nextPolicy,
by, reason, Instant.now().toString(), humanApproved);
if (nextMode == Mode.UNSPECIFIED) throw ProtocolException.invalid("Ask the human to choose DIRECT or EXPLORATORY");
var choices = new ArrayList<>(history); choices.add(choice);
return new WorkGuidance(choice.mode(), choice.approvalPolicy(), choices, decisionRequests);
}
public WorkGuidance request(String decision, String by, String reason, boolean humanApproved) {
requireMode(); var request = new Request(decision, by, reason, Instant.now().toString(), humanApproved);
if (decisionRequests.stream().anyMatch(r -> r.decisionId().equals(decision))) return this;
var requests = new ArrayList<>(decisionRequests); requests.add(request);
return new WorkGuidance(mode, approvalPolicy, history, requests);
}
public void requireMode() {
if (mode == Mode.UNSPECIFIED) throw ProtocolException.invalid("Ask the human for DIRECT or EXPLORATORY; record with work guidance before creating a DEC or Plan");
}
public void requireDecisionRequest(String decision) {
requireMode();
if (mode == Mode.EXPLORATORY && decisionRequests.stream().noneMatch(r -> r.decisionId().equals(decision)))
throw ProtocolException.invalid("Exploratory discussion remains open: the human must request " + decision + " with work request-decision");
}
public boolean waived() { return approvalPolicy == ApprovalPolicy.WAIVED; }
public String instructions() {
String conduct = switch (mode) {
case UNSPECIFIED -> "Ask the human to choose DIRECT or EXPLORATORY. Never infer the preference.";
case DIRECT -> "Resolve essential questions, prepare the DEC, then request the applicable approval. Suggest EXPLORATORY if many unknowns emerge; only the human changes the mode.";
case EXPLORATORY -> "Challenge the framing and assumptions; compare alternatives and synthesize established points, viable paths, fragile premises and unknowns. Suggest when mature, but only the human ends discussion and requests each DEC.";
};
return conduct + (waived() ? " Human instruction explicitly waives DEC approval for this Work only; system promotion is not human approval."
: " Human approval of the concrete DEC is required before creating or executing its Plan; direct mode never waives approval.")
+ " Execute autonomously within the DEC. Identify relevant experiments, hypotheses and success criteria before running them. Record evidence, interpretation and next action; reconsider failed hypotheses before retrying. If evidence questions the DEC, continue authorized investigation and independent work, and revise the DEC with applicable approval before contradicting it.";
}
}
@@ -35,6 +35,12 @@ public final class WorkService {
List<String> constraints, List<String> criteria, List<String> repositories, String author) {
return createPrepared(root, title, description, goal, motivation, constraints, criteria, repositories, author, (folder, work) -> work);
}
public Work create(Path root, String title, String description, String goal, String motivation,
List<String> constraints, List<String> criteria, List<String> repositories, String author, WorkGuidance initial) {
if (initial != null && !guidanceContract(root)) throw ProtocolException.invalid("Explicit Work guidance requires contract 3; inspect compatibility and run onboard");
return createPrepared(root, title, description, goal, motivation, constraints, criteria, repositories, author,
(folder, work) -> initial == null ? work : work.withGuidance(initial));
}
/** Build initial child records before the Work becomes visible to readers. Caller shares the project lock. */
public Work createPrepared(Path root, String title, String description, String goal, String motivation,
List<String> constraints, List<String> criteria, List<String> repositories, String author,
@@ -52,6 +58,7 @@ public final class WorkService {
var work = new Work(1, id, title, description, goal.isBlank() ? title : goal, motivation, constraints, criteria,
Work.Status.OPEN, now, now, author, projects.revisions(root, repositories), 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());
Path target = Filespace.resolve(workspace(root), id + "-" + ProjectService.slug(title));
Path staging = Filespace.resolve(workspace(root), "." + id + "-" + UUID.randomUUID() + ".tmp");
Filespace.directory(staging);
@@ -100,6 +107,35 @@ public final class WorkService {
});
}
public Work editable(Path root, String id) { Work work = load(root, id); work.requireEditable(); return work; }
private boolean guidanceContract(Path root) {
Path path = Filespace.resolve(root, ".ai-engineering/protocol.json");
return Files.exists(path) && net.intrepid.aiengineering.project.ProtocolContract.effective(
Documents.readJson(path, net.intrepid.aiengineering.project.ProtocolGuide.Manifest.class).protocolVersion()) >= 3;
}
public Work guidance(Path root, String id, WorkGuidance.Mode mode, WorkGuidance.ApprovalPolicy policy,
String by, String reason, boolean humanApproved) {
return Filespace.locked(root, () -> {
if (!guidanceContract(root)) throw ProtocolException.invalid("Work guidance requires contract 3; inspect compatibility and run onboard");
var work = editable(root, id);
if (mode == null && policy == null) throw ProtocolException.invalid("Specify --mode or --approval");
var old = work.guidance() == null ? WorkGuidance.pending() : work.guidance();
var updated = work.withGuidance(old.choose(mode, policy, by, reason, humanApproved)); save(root, updated); return updated;
});
}
public Work requestDecision(Path root, String id, String by, String reason, boolean humanApproved) {
return requestDecision(root, id, null, by, reason, humanApproved);
}
public Work requestDecision(Path root, String id, String decision, String by, String reason, boolean humanApproved) {
return Filespace.locked(root, () -> {
var work = editable(root, id);
if (work.guidance() == null) throw ProtocolException.invalid("Record the human's mode with work guidance first");
String target = decision == null ? nextReference(work.decisions(), "DEC") : decision;
if (!target.equals(nextReference(work.decisions(), "DEC")) && !work.decisions().contains(target))
throw ProtocolException.invalid("Request must name an existing DEC or the next DEC in this Work");
var updated = work.withGuidance(work.guidance().request(target, by, reason, humanApproved));
save(root, updated); return updated;
});
}
public Work markEpic(Path root, String id) {
return Filespace.locked(root, () -> { var work = load(root, id).asEpic(); save(root, work); return work; });
}