package net.intrepid.aiengineering.cli; 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 net.intrepid.aiengineering.verification.*; import picocli.CommandLine; import picocli.CommandLine.*; import java.io.PrintWriter; import java.nio.file.Path; import java.nio.file.Files; import java.util.List; @Command(name = "ai-engineering", description = "Portable engineering protocol for humans and AI agents.", mixinStandardHelpOptions = true, version = "ai-engineering " + ProtocolContract.CLI_VERSION) public final class EngineeringCli implements Runnable { private final Path cwd; private final ProjectService projects = new ProjectService(); private final WorkService works = new WorkService(); private final VerificationService verification = new VerificationService(); private PrintWriter output; private CommandLine commandLine; private final java.io.Reader input; private final boolean injectedInput; @Option(names = "--project", scope = ScopeType.INHERIT, description = "Engineering project root or .ai-engineering directory.") Path project; public EngineeringCli(Path cwd) { this(cwd, new java.io.InputStreamReader(System.in, java.nio.charset.StandardCharsets.UTF_8), false); } public EngineeringCli(Path cwd, java.io.Reader input) { this(cwd, input, true); } private EngineeringCli(Path cwd, java.io.Reader input, boolean injectedInput) { this.cwd = cwd.toAbsolutePath().normalize(); this.input = input; this.injectedInput = injectedInput; } public int execute(PrintWriter out, PrintWriter err, String... args) { output = out; commandLine = new CommandLine(this) .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("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())); configure(commandLine, out, err); commandLine.setExecutionExceptionHandler((exception, command, parse) -> { if (exception instanceof ProtocolException problem) { err.println(problem.getMessage()); return problem.exitCode(); } if (exception instanceof IllegalArgumentException) { err.println("Invalid input: " + exception.getMessage()); return 2; } err.println("Operation failed: " + exception.getMessage()); return 1; }); int result = commandLine.execute(args); out.flush(); err.flush(); return result; } private void configure(CommandLine command, PrintWriter out, PrintWriter err) { command.setOut(out).setErr(err).setCaseInsensitiveEnumValuesAllowed(true); command.getSubcommands().values().forEach(child -> configure(child, out, err)); } @Override public void run() { commandLine.usage(output); } private Path discoveredRoot() { return projects.discover(cwd, project == null ? null : resolve(project)); } private Path root() { Path root = discoveredRoot(); ProtocolGuide.requireSupportedVersion(root); return root; } private Path resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); } enum Format { markdown, json } @Command(name = "import", mixinStandardHelpOptions = true, description = "Import supported legacy context with explicit preview and application.") public class ImportCommands implements Runnable { @Override public void run() { commandLine.getSubcommands().get("import").usage(output); } } @Command(name = "discussion", mixinStandardHelpOptions = true, description = "Preview or import DF DSCs with open AGD agendas, without a model call.") public class DiscussionImportCommand implements java.util.concurrent.Callable { @Option(names = "--source", required = true, description = "Stable source ID=PATH; repeat for independent DF projects. Paths are caller-relative.") List sources; @Option(names = "--target", description = "SOURCE=TEXT target description; repeat for multiple targets.") List targets; @Option(names = "--apply", description = "Publish the reviewed import; requires --expect.") boolean apply; @Option(names = "--expect", description = "Fingerprint returned by a valid preview.") String expected; @Option(names = "--author", defaultValue = "human") String author; @Option(names = "--format", defaultValue = "markdown") Format format; private String[] pair(String value, String option) { int at = value.indexOf('='); if (at < 1 || at == value.length() - 1) throw ProtocolException.invalid(option + " requires ID=VALUE"); return new String[]{value.substring(0, at), value.substring(at + 1)}; } @Override public Integer call() { if (apply && expected == null) throw ProtocolException.invalid("--apply requires --expect from a preview"); if (!apply && expected != null) throw ProtocolException.invalid("--expect requires --apply"); var roots = new java.util.LinkedHashMap(); var targetMap = new java.util.HashMap>(); for (String raw : sources) { var pair = pair(raw, "--source"); if (roots.putIfAbsent(pair[0], resolve(Path.of(pair[1])).normalize().toString()) != null) throw ProtocolException.invalid("Duplicate source ID: " + pair[0]); } for (String raw : safe(targets)) { var pair = pair(raw, "--target"); if (!roots.containsKey(pair[0])) throw ProtocolException.invalid("Unknown target source: " + pair[0]); targetMap.computeIfAbsent(pair[0], k -> new java.util.ArrayList<>()).add(pair[1]); } var inputs = roots.entrySet().stream().map(e -> new net.intrepid.aiengineering.legacyimport.DiscussionImport.Source(e.getKey(), e.getValue(), targetMap.get(e.getKey()))).toList(); var importer = new net.intrepid.aiengineering.legacyimport.DiscussionImportService(); Path destination = root(); if (apply) { var validity = verification.project(destination); if (!validity.valid()) throw ProtocolException.validation(String.join("; ", validity.issues())); } var result = apply ? importer.apply(destination, inputs, expected, author) : importer.preview(destination, inputs); if (format == Format.json) output.print(Documents.json(result)); else output.print(net.intrepid.aiengineering.legacyimport.DiscussionImportService.markdown(result)); return result.valid() ? 0 : 4; } } private int emit(Object value, Format format) { output.print(format == Format.json ? Documents.json(value) : Documents.yaml(value)); return 0; } private int report(ValidationReport report, Format format) { emit(report, format); return report.valid() ? 0 : 4; } private int lifecycle(EpicCoordinator.LifecycleResult result, Format format) { return emit(result.propagation().epics().isEmpty() ? result.work() : result, format); } private int change(String work, String by, java.util.function.Supplier mutation, Format format) { var changed = new PlanCoordinator().change(root(), work, by, null, mutation); Object value = changed.result(); if (value instanceof Plan plan) value = new PlanService().get(root(), work, plan.id()); return emit(works.load(root(), work).plans().isEmpty() ? value : new PlanCoordinator.Mutation<>(value, changed.coordination()), format); } private void afterChange(String work, String by) { if (works.load(root(), work).plans().isEmpty()) return; try { emit(new PlanCoordinator().reconcile(root(), work, by, null), Format.markdown); } catch (RuntimeException failure) { throw PlanCoordinator.persisted(work, failure); } } @Command(name = "init", mixinStandardHelpOptions = true, description = "Initialize protocol files in this project folder; Git is optional.") int init(@Parameters(index = "0", arity = "0..1", description = "Project directory; default is the current directory.") Path directory, @Option(names = "--name") String name, @Option(names = "--general-adapter", description = "Configure an available adapter without calling it.") String generalAdapter, @Option(names = "--archive-policy", description = "review-only or reversible; requires an executor.") String archivePolicy, @Option(names = "--interactive", description = "Guide project and executor setup before writing files.") boolean interactive, @Option(names = "--input-file", description = "Explicit UTF-8 answers for guided setup.") Path inputFile) { if (project != null && directory != null) throw ProtocolException.invalid("Use a project directory or --project, not both"); Path target = project != null ? resolve(project) : directory != null ? resolve(directory) : cwd; boolean guided = interactive || inputFile != null || (name == null && (injectedInput || System.console() != null)); if (guided) { if (generalAdapter != null) throw ProtocolException.invalid("Use guided setup or --general-adapter, not both"); if (inputFile == null && !injectedInput && System.console() == null) throw ProtocolException.invalid("Guided setup requires a console or --input-file"); var reader = inputFile == null ? input : new java.io.StringReader(readDiscussionText(resolve(inputFile))); Path filename = target.toAbsolutePath().normalize().getFileName(); var setup = new ProjectSetup(reader, output).collect(name, filename == null ? "Engineering Project" : filename.toString(), archivePolicy); var initialized = projects.initialize(target, setup.name()); if (setup.agents() == null) return emit(initialized, Format.markdown); return emit(projects.configureAgents(projects.discover(target, null), setup.agents()), Format.markdown); } if (name == null) throw ProtocolException.invalid("Supply --name or use --interactive setup"); if (generalAdapter == null && archivePolicy != null) throw ProtocolException.invalid("--archive-policy requires --general-adapter"); if (generalAdapter != null) { if (new AgentService().available().stream().noneMatch(a -> a.id().equals(generalAdapter))) throw ProtocolException.invalid("Unknown adapter: " + generalAdapter); new ProjectConfig.Agents(new ProjectConfig.Executor(generalAdapter,"general","default"), java.util.Map.of(), archivePolicy == null ? "review-only" : archivePolicy); } var initialized = projects.initialize(target, name); if (generalAdapter != null) return emit(new AgentService().configure(projects.discover(target, null), "general", generalAdapter, null, null, archivePolicy), Format.markdown); return emit(initialized, Format.markdown); } @Command(name = "onboard", mixinStandardHelpOptions = true, description = "Install or refresh portable agent instructions, backing up changed files.") int onboard(@Option(names = "--format", defaultValue = "markdown") Format format) { Path root = root(); projects.load(root); return emit(ProtocolGuide.install(root), format); } @Command(name = "guide", mixinStandardHelpOptions = true, description = "Read the protocol guide or machine-readable discovery manifest.") int guide(@Option(names = "--format", defaultValue = "markdown") Format format) { output.print(ProtocolGuide.bundled(format == Format.json ? "protocol.json" : "README.md")); return 0; } @Command(name = "status", mixinStandardHelpOptions = true, description = "Inspect Works, validation and suggested next actions.") int status(@Option(names = "--all", description = "Include archived Works.") boolean all, @Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) { Path root = root(); if (format == Listing.Format.json) return emit(verification.status(root, all), Format.json); var state = new CompatibilityService().inspect(root).summary(); var selected = works.list(root).stream().filter(w -> all || !w.archived()).toList(); if (format != Listing.Format.csv) { String name = projects.load(root).project().name(); String details = (format == Listing.Format.markdown ? Listing.markdown(name) : Listing.singleLine(name)) + " | Onboarded: " + ProtocolGuide.installed(root) + " | Compatibility: " + state.state(); output.println(format == Listing.Format.markdown ? "# Project status\n\n" + details + "\n" : details + "\n"); } output.print(Listing.works(verification.overview(root, selected), format)); return 0; } @Command(name = "next-actions", mixinStandardHelpOptions = true, description = "Suggest deterministic next actions; does not execute them.") int nextActions(@Parameters(index = "0", arity = "0..1") String id, @Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) { var actions = verification.nextActions(root(), id); if (format == Listing.Format.json) return emit(actions, Format.json); output.print(Listing.actions(actions, format)); return 0; } @Command(name = "project", mixinStandardHelpOptions = true, description = "Inspect and validate the engineering project.") public class ProjectCommands { @Command(name = "compatibility", mixinStandardHelpOptions = true, description = "Inspect contract and stored formats without writing or migrating historical Works.") int compatibility(@Option(names = "--format", defaultValue = "markdown") Format format) { var result = new CompatibilityService().inspect(discoveredRoot()); emit(result, format); return result.readable() ? 0 : 4; } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()), format); } @Command(name = "validate", mixinStandardHelpOptions = true) int validate(@Option(names = "--format", defaultValue = "markdown") Format format) { return report(verification.project(root()), format); } } @Command(name = "repo", mixinStandardHelpOptions = true, description = "Register existing source repositories; default access is read-only.") public class RepoCommands { @Command(name = "add", mixinStandardHelpOptions = true) int add(@Parameters(index = "0") String id, @Option(names = "--path", required = true, description = "Path relative to the project root; use . for the root repository.") String path, @Option(names = "--type", defaultValue = "linked-git") String type, @Option(names = "--language") String language, @Option(names = "--allow-edit") boolean edit, @Option(names = "--validation-command") List commands) { var repo = new ProjectConfig.Repository(id, path, type, language, new ProjectConfig.Access(true, edit), commands); return emit(projects.addRepository(root(), repo), Format.markdown); } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()).repositories(), format); } } @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, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new PlanCoordinator().reconcile(root(), id, requester, requestId), format); } @Command(name = "create", mixinStandardHelpOptions = true) int create(@Parameters(index = "0") String title, @Option(names = "--description", defaultValue = "") String description, @Option(names = "--goal", defaultValue = "") String goal, @Option(names = "--motivation", defaultValue = "") String motivation, @Option(names = "--constraint") List constraints, @Option(names = "--acceptance") List criteria, @Option(names = "--repo") List repositories, @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, @Option(names = "--format", defaultValue = "markdown", description = "Output: ${COMPLETION-CANDIDATES}.") Listing.Format format) { Path root = root(); var selected = works.list(root).stream().filter(w -> !open || (!w.terminal() && !w.archived())).toList(); if (format == Listing.Format.json) return emit(selected, Format.json); output.print(Listing.works(verification.overview(root, selected), format)); return 0; } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(works.load(root(), id), format); } @Command(name = "update", mixinStandardHelpOptions = true, description = "Update specified Work fields, preserving history and references.") int update(@Parameters(index = "0") String id, @Option(names = "--title") String title, @Option(names = "--description") String description, @Option(names = "--goal") String goal, @Option(names = "--motivation") String motivation, @Option(names = "--constraint", description = "Replace all constraints; repeat for multiple values.") List constraints, @Option(names = "--acceptance", description = "Replace all acceptance criteria; repeat for multiple values.") List criteria, @Option(names = "--clear-constraints", description = "Remove all constraints.") boolean clearConstraints, @Option(names = "--clear-acceptance", description = "Remove all acceptance criteria.") boolean clearCriteria, @Option(names = "--format", defaultValue = "markdown") Format format) { if (clearConstraints && constraints != null) throw ProtocolException.invalid("Use --constraint or --clear-constraints, not both"); if (clearCriteria && criteria != null) throw ProtocolException.invalid("Use --acceptance or --clear-acceptance, not both"); var change = new Work.Update(title, description, goal, motivation, clearConstraints ? List.of() : constraints, clearCriteria ? List.of() : criteria); return lifecycle(verification.update(root(), id, change), format); } @Command(name = "validate", mixinStandardHelpOptions = true) int validate(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { Work.identifier(id, "WRK"); Path root = root(); works.load(root, id); return report(verification.work(root, id), format); } @Command(name = "context", mixinStandardHelpOptions = true) int context(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { Work.identifier(id, "WRK"); Path root = root(); works.load(root, id); var context = verification.context(root, id); output.print(format == Format.json ? Documents.json(context) : verification.markdown(context)); return 0; } @Command(name = "status", mixinStandardHelpOptions = true, description = "Set open Work status; use complete/reopen for reviewed closure and resumption.") int status(@Parameters(index = "0") String id, @Parameters(index = "1") Work.Status status, @Option(names = "--by", defaultValue = "human") String by, @Option(names = "--reason") String reason, @Option(names = "--requester") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { return lifecycle(verification.status(root(), id, status, by, reason == null ? "Status set to " + status : reason, requester == null ? by : requester, requestId), format); } @Command(name = "check", mixinStandardHelpOptions = true, description = "Check mechanical completion readiness; evidence still needs human review.") int check(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { Path root = root(); works.load(root, id); return report(verification.readiness(root, id), format); } @Command(name = "complete", mixinStandardHelpOptions = true, description = "Record human-approved completion, criterion evidence and canonical integration.") int complete(@Parameters(index = "0") String id, @Option(names = "--by", required = true) String by, @Option(names = "--summary", required = true) String summary, @Option(names = "--human-approved", required = true) boolean humanApproved, @Option(names = "--criterion", description = "Evidence mapping N=ART-0001[,ART-0002]; repeat for every criterion.") List criteria, @Option(names = "--integration", description = "Updated canonical file, relative to project root; repeat as needed.") List integrations, @Option(names = "--no-integration-needed", description = "Explain why no canonical knowledge update is necessary.") String noIntegrationReason, @Option(names = "--requester") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { return lifecycle(verification.completeWithPropagation(root(), id, by, summary, humanApproved, safe(criteria), safe(integrations), noIntegrationReason, requester == null ? by : requester, requestId), format); } @Command(name = "archive", mixinStandardHelpOptions = true, description = "Archive a terminal Work while retaining all records and evidence.") int archive(@Parameters(index = "0") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return emit(verification.archive(root(), id, by, reason), Format.markdown); } @Command(name = "reopen", mixinStandardHelpOptions = true, description = "Resume a terminal Work, preserving earlier completion records.") int reopen(@Parameters(index = "0") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--requester") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { return lifecycle(verification.reopen(root(), id, by, reason, requester == null ? by : requester, requestId), format); } } @Command(name = "discussion", mixinStandardHelpOptions = true, description = "Append human or agent refinement entries.") public class DiscussionCommands { @Command(name = "add", mixinStandardHelpOptions = true) int add(@Parameters(index = "0") String id, @ArgGroup(exclusive = true, multiplicity = "1") DiscussionText input, @Option(names = "--kind", defaultValue = "NOTE") DiscussionEntry.Kind kind, @Option(names = "--author", defaultValue = "human") String author, @Option(names = {"--discussion", "--topic"}, defaultValue = "main") String thread, @Option(names = "--responds-to") String respondsTo) { String text = input.text != null ? input.text : readDiscussionText(resolve(input.file)); var entry = new DiscussionService().add(root(), id, text, kind, author, thread, respondsTo); output.print(Documents.markdownDocument(entry, "text")); afterChange(id, author); return 0; } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var entries = new DiscussionService().list(root(), id); if (format == Format.json) return emit(entries, format); output.println(verification.discussionMarkdown(entries)); return 0; } @Command(name = "migrate", mixinStandardHelpOptions = true, description = "Convert legacy discussion prose to Markdown bodies, backing up originals in .local.") int migrate(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new DiscussionService().migrate(root(), id), format); } @Command(name = "archive", mixinStandardHelpOptions = true, description = "Archive a proposal reversibly under the configured policy, with evidence.") int archive(@Parameters(index = "0") String work, @Parameters(index = "1") String entry, @Option(names = "--reason", required = true) String reason, @Option(names = "--evidence", required = true) List evidence, @Option(names = "--by", defaultValue = "human") String by) { return emit(new DispositionService().apply(root(), work, entry, Disposition.Action.ARCHIVE, reason, evidence, by), Format.markdown); } @Command(name = "restore", mixinStandardHelpOptions = true) int restore(@Parameters(index = "0") String work, @Parameters(index = "1") String entry, @Option(names = "--reason", required = true) String reason, @Option(names = "--by", defaultValue = "human") String by) { return emit(new DispositionService().apply(root(), work, entry, Disposition.Action.RESTORE, reason, List.of(), by), Format.markdown); } } @Command(name = "decision", mixinStandardHelpOptions = true, description = "Refine, review and revise formal decisions with preserved history.") public class DecisionCommands { @Command(name = "draft", mixinStandardHelpOptions = true) int draft(@Parameters(index = "0") String id, @Option(names = "--title", required = true) String title, @Option(names = "--context", defaultValue = "") String context, @Option(names = "--approach", defaultValue = "") String approach, @Option(names = "--rationale", defaultValue = "") String rationale, @Option(names = "--evidence") List evidence, @Option(names = "--author", defaultValue = "human") String author, @Option(names = "--text") String text, @Option(names = "--text-file") Path textFile) { String narrative = optionalText(text, textFile); var decision = new DecisionService().draft(root(), id, title, context, approach, rationale, safe(evidence), author, narrative == null ? "" : narrative); output.print(Documents.markdownDocument(decision, "text")); return 0; } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var all = new DecisionService().list(root(), id); if (format == Format.json) return emit(all, format); output.println(verification.decisionMarkdown(all)); return 0; } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var decision = new DecisionService().get(root(), work, id); if (format == Format.json) return emit(decision, format); output.print(Documents.markdownDocument(decision, "text")); return 0; } @Command(name = "history", mixinStandardHelpOptions = true) int history(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new DecisionService().history(root(), work, id), format); } @Command(name = "update", mixinStandardHelpOptions = true, description = "Edit a draft; snapshot the previous revision.") int update(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--title") String title, @Option(names = "--context") String context, @Option(names = "--approach") String approach, @Option(names = "--rationale") String rationale, @Option(names = "--alternative") List alternatives, @Option(names = "--risk") List risks, @Option(names = "--acceptance") List criteria, @Option(names = "--evidence") List evidence, @Option(names = "--clear-alternatives") boolean clearAlternatives, @Option(names = "--clear-risks") boolean clearRisks, @Option(names = "--clear-acceptance") boolean clearCriteria, @Option(names = "--clear-evidence") boolean clearEvidence, @Option(names = "--text") String text, @Option(names = "--text-file") Path textFile) { var change = new Decision.Update(title, context, approach, rationale, replacement(alternatives, clearAlternatives), replacement(risks, clearRisks), replacement(criteria, clearCriteria), replacement(evidence, clearEvidence), optionalText(text, textFile)); var decision = new DecisionService().update(root(), work, id, change, by, reason); output.print(Documents.markdownDocument(decision, "text")); return 0; } @Command(name = "accept", mixinStandardHelpOptions = true, description = "Attest explicit human approval; never infer it from agent output.") int accept(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--human-approved", required = true) boolean humanApproved) { return change(work, by, () -> new DecisionService().accept(root(), work, id, by, reason, humanApproved), Format.markdown); } @Command(name = "reject", mixinStandardHelpOptions = true) int reject(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return change(work, by, () -> new DecisionService().reject(root(), work, id, by, reason), Format.markdown); } @Command(name = "revise", mixinStandardHelpOptions = true, description = "Create a new draft linked to the accepted or rejected decision.") int revise(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { 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 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 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 decisions, @Option(names = "--author", defaultValue = "human") String author) { return change(work, author, () -> new PlanService().create(root(), work, title, description, safe(decisions), author), Format.markdown); } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new PlanService().list(root(), work), format); } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new PlanService().get(root(), work, id), format); } @Command(name = "history", mixinStandardHelpOptions = true) int history(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new PlanService().history(root(), work, id), format); } @Command(name = "update", mixinStandardHelpOptions = true) int update(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--title") String title, @Option(names = "--description") String description, @Option(names = "--decision") List decisions, @Option(names = "--clear-decisions") boolean clearDecisions, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return change(work, by, () -> new PlanService().update(root(), work, id, title, description, replacement(decisions, clearDecisions), by, reason), Format.markdown); } @Command(name = "status", mixinStandardHelpOptions = true) int status(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Parameters(index = "2") Plan.Status status, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--format", defaultValue = "markdown") Format format) { return change(work, by, () -> new PlanService().status(root(), work, id, status, by, reason), format); } @Command(name = "exclude", mixinStandardHelpOptions = true, description = "Review cancelled scope and exclude the exact Plan/step content, retaining history.") int exclude(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--step") String step, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--format", defaultValue = "markdown") Format format) { return change(work, by, () -> new PlanService().exclude(root(), work, id, step, by, reason), format); } } @Command(name = "step", mixinStandardHelpOptions = true, description = "Track steps, dependencies, results and evidence.") public class StepCommands { @Command(name = "add", mixinStandardHelpOptions = true) int add(@Parameters(index = "0") String work, @Parameters(index = "1") String plan, @Option(names = "--title", required = true) String title, @Option(names = "--description", defaultValue = "") String description, @Option(names = "--acceptance") List criteria, @Option(names = "--depends-on") List deps, @Option(names = "--by", defaultValue = "human") String by, @Option(names = "--reason", defaultValue = "Step added") String reason) { return change(work, by, () -> new PlanService().addStep(root(), work, plan, title, description, safe(criteria), safe(deps), by, reason), Format.markdown); } @Command(name = "update", mixinStandardHelpOptions = true) int update(@Parameters(index = "0") String work, @Parameters(index = "1") String plan, @Parameters(index = "2") String step, @Option(names = "--title") String title, @Option(names = "--description") String description, @Option(names = "--acceptance") List criteria, @Option(names = "--depends-on") List deps, @Option(names = "--clear-acceptance") boolean clearCriteria, @Option(names = "--clear-dependencies") boolean clearDeps, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return change(work, by, () -> new PlanService().updateStep(root(), work, plan, step, title, description, replacement(criteria, clearCriteria), replacement(deps, clearDeps), by, reason), Format.markdown); } @Command(name = "status", mixinStandardHelpOptions = true) int status(@Parameters(index = "0") String work, @Parameters(index = "1") String plan, @Parameters(index = "2") String step, @Parameters(index = "3") Plan.Status status, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--evidence") List evidence, @Option(names = "--format", defaultValue = "markdown") Format format) { return change(work, by, () -> new PlanService().stepStatus(root(), work, plan, step, status, by, reason, safe(evidence)), format); } } @Command(name = "topic", mixinStandardHelpOptions = true, description = "Organize Discussion within a Work; legacy threads remain readable.") public class TopicCommands { @Command(name = "create", mixinStandardHelpOptions = true) int create(@Parameters(index = "0") String work, @Parameters(index = "1") String title, @Option(names = "--description", defaultValue = "") String description, @Option(names = "--source") List sources, @Option(names = "--author", defaultValue = "human") String author) { var topic = new TopicService().create(root(), work, title, description, safe(sources), author); output.print(Documents.markdownDocument(topic, "description")); return 0; } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new TopicService().views(root(), work), format); } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var topic = new TopicService().views(root(), work).stream().filter(t -> t.id().equals(id)).findFirst().orElseThrow(() -> ProtocolException.missing("Topic not found: " + id)); return emit(topic, format); } @Command(name = "update", mixinStandardHelpOptions = true) int update(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--title") String title, @Option(names = "--description") String description, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { var topic = new TopicService().update(root(), work, id, title, description, by, reason); output.print(Documents.markdownDocument(topic, "description")); return 0; } } @Command(name = "survey", mixinStandardHelpOptions = true, description = "Questions with suggestions, free text and versioned answers.") public class SurveyCommands { @Command(name = "create", mixinStandardHelpOptions = true) int create(@Parameters(index = "0") String work, @Option(names = "--title", required = true) String title, @Option(names = "--description", defaultValue = "") String description, @Option(names = "--author", defaultValue = "human") String author) { var survey = new SurveyService().create(root(), work, title, description, author); output.print(Documents.markdownDocument(survey, "description")); return 0; } @Command(name = "list", mixinStandardHelpOptions = true) int list(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new SurveyService().list(root(), work), format); } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var survey = new SurveyService().get(root(), work, id); if (format == Format.json) return emit(survey, format); output.print(verification.surveyMarkdown(survey)); return 0; } @Command(name = "history", mixinStandardHelpOptions = true) int history(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new SurveyService().history(root(), work, id), format); } @Command(name = "question", mixinStandardHelpOptions = true) int question(@Parameters(index = "0") String work, @Parameters(index = "1") String survey, @Option(names = "--topic") String topic, @Option(names = "--text", required = true) String text, @Option(names = "--option", required = true) List options, @Option(names = "--multiple") boolean multiple, @Option(names = "--recommend") String recommend, @Option(names = "--source") List sources, @Option(names = "--author", defaultValue = "human") String author) { Path root = root(); String selected = topic == null ? new TopicService().views(root, work).getFirst().id() : topic; return emit(new SurveyService().question(root, work, survey, selected, text, options, multiple, recommend, safe(sources), author), Format.markdown); } @Command(name = "answer", mixinStandardHelpOptions = true) int answer(@Parameters(index = "0") String work, @Parameters(index = "1") String survey, @Parameters(index = "2") String question, @Option(names = "--choice") List choices, @Option(names = "--text") String text, @Option(names = "--text-file") Path file, @Option(names = "--author", defaultValue = "human") String author) { return change(work, author, () -> new SurveyService().answer(root(), work, survey, question, safe(choices), optionalText(text, file), author), Format.markdown); } @Command(name = "ask", mixinStandardHelpOptions = true, description = "Answer pending questions using a console or explicit UTF-8 input file.") int ask(@Parameters(index = "0") String work, @Parameters(index = "1") String survey, @Option(names = "--input-file") Path file, @Option(names = "--author", defaultValue = "human") String author) { if (file == null && !injectedInput && System.console() == null) throw ProtocolException.invalid("Guided answering requires a console or --input-file; use survey answer for noninteractive calls"); var reader = new java.io.BufferedReader(file == null ? input : new java.io.StringReader(readDiscussionText(resolve(file)))); Path root = root(); var service = new SurveyService(); for (var question : service.get(root, work, survey).pending()) { output.println(question.topicId() + " / " + question.id() + ": " + question.text()); for (var option : question.options()) output.println(" " + option.id() + ". " + option.text() + (option.id().equals(question.recommendedOption()) ? " (suggested)" : "")); output.println("Choose number(s), or write freely. Prefix numeric free text with text: ."); output.flush(); String line = Filespace.io(reader::readLine); if (line == null) throw ProtocolException.invalid("Input ended before pending questions were answered"); String value = line.strip(); var choices = value.matches("[1-9][0-9]*(,[1-9][0-9]*)*") ? List.of(value.split(",")) : List.of(); service.answer(root, work, survey, question.id(), choices, choices.isEmpty() ? value.startsWith("text:") ? line.substring(line.indexOf("text:")+5) : line : "", author); } output.println("All pending questions answered."); afterChange(work, author); return 0; } } @Command(name = "agent", mixinStandardHelpOptions = true, description = "Configure fixtures or local proposal-only Codex/Claude adapters.") public class AgentCommands { @Command(name = "list", mixinStandardHelpOptions = true) int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new AgentService().available(), format); } @Command(name = "doctor", mixinStandardHelpOptions = true, description = "Probe local CLI version/help; no model request is sent.") int doctor(@Option(names = "--adapter") String adapter, @Option(names = "--format", defaultValue = "markdown") Format format) { var reports = new AgentService().doctors(adapter); emit(reports, format); return reports.stream().anyMatch(r -> !r.installed()) ? 3 : reports.stream().anyMatch(r -> !r.compatible()) ? 4 : 0; } @Command(name = "configure", mixinStandardHelpOptions = true) int configure(@Option(names = "--adapter", required = true) String adapter, @Option(names = "--activity", defaultValue = "general") String activity, @Option(names = "--profile") String profile, @Option(names = "--model") String model, @Option(names = "--timeout", description = "Provider timeout in seconds (1–600; default 120).") Integer timeout, @Option(names = "--archive-policy") String policy) { return emit(new AgentService().configure(root(), activity, adapter, profile, model, policy, timeout), Format.markdown); } @Command(name = "run", mixinStandardHelpOptions = true) int run(@Parameters(index = "0") String work, @Option(names = "--task") String task, @Option(names = "--task-file") Path file, @Option(names = "--activity") String activity, @Option(names = "--requester", defaultValue = "human") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { String text = optionalText(task, file); if (text == null) throw ProtocolException.invalid("Supply --task or --task-file"); var run = new AgentService().run(root(), work, text, activity, requester, requestId); if (!works.load(root(), work).plans().isEmpty()) { try { return emit(new PlanCoordinator.Mutation<>(run, new PlanCoordinator().reconcile(root(), work, requester, requestId)), format); } catch (RuntimeException failure) { throw PlanCoordinator.persisted(work, failure); } } if (format == Format.json) return emit(run, format); output.print(Documents.markdownDocument(run, "task")); return 0; } @Command(name = "history", mixinStandardHelpOptions = true) int history(@Parameters(index = "0") String work, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new AgentService().views(root(), work), format); } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String work, @Parameters(index = "1") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var run = new AgentService().get(root(), work, id); if (format == Format.json) return emit(run, format); output.print(Documents.markdownDocument(run, "task")); return 0; } } @Command(name = "epic", mixinStandardHelpOptions = true, description = "Coordinate related Works with deterministic, explicitly authorized completion rules.") public class EpicCommands { @Command(name = "configure", mixinStandardHelpOptions = true) int configure(@Parameters(index = "0") String id, @Option(names = "--mode", defaultValue = "RESULTS") Epic.Mode mode, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return emit(new EpicService().configure(root(), id, mode, by, reason), Format.markdown); } @Command(name = "link", mixinStandardHelpOptions = true) int link(@Parameters(index = "0") String id, @Parameters(index = "1") String child, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return emit(new EpicService().link(root(), id, child, by, reason), Format.markdown); } @Command(name = "unlink", mixinStandardHelpOptions = true) int unlink(@Parameters(index = "0") String id, @Parameters(index = "1") String child, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { return emit(new EpicService().unlink(root(), id, child, by, reason), Format.markdown); } @Command(name = "importance", mixinStandardHelpOptions = true) int importance(@Parameters(index = "0") String id, @Parameters(index = "1") String child, @Option(names = "--important") boolean important, @Option(names = "--optional") boolean optional, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason) { if (important == optional) throw ProtocolException.invalid("Choose --important or --optional"); return emit(new EpicService().importance(root(), id, child, important, by, reason), Format.markdown); } @Command(name = "authorize", mixinStandardHelpOptions = true, description = "Record explicit human delegation for the aggregate condition and check it.") int authorize(@Parameters(index = "0") String id, @Option(names = "--by", required = true) String by, @Option(names = "--reason", required = true) String reason, @Option(names = "--human-approved", required = true) boolean approved, @Option(names = "--requester") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { String key = EpicCoordinator.correlation(requestId); Path root = root(); return Filespace.locked(root, () -> { new EpicService().authorize(root, id, by, reason, approved); return emit(new EpicCoordinator().reconcile(root, id, requester == null ? by : requester, key), format); }); } @Command(name = "show", mixinStandardHelpOptions = true) int show(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new EpicCoordinator().inspect(root(), id), format); } @Command(name = "check", mixinStandardHelpOptions = true, description = "Inspect pending conditions without applying a transition.") int check(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { var evaluation = new EpicCoordinator().inspect(root(), id); emit(evaluation, format); return evaluation.ready() ? 0 : 4; } @Command(name = "history", mixinStandardHelpOptions = true) int history(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { Path root = root(); new EpicService().get(root, id); return emit(new EpicService().history(root, id), format); } @Command(name = "reconcile", mixinStandardHelpOptions = true, description = "Recover missed propagation from canonical files; no model is invoked.") int reconcile(@Parameters(index = "0", arity = "0..1") String id, @Option(names = "--requester", defaultValue = "human") String requester, @Option(names = "--request-id") String requestId, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(new EpicCoordinator().reconcile(root(), id, requester, requestId), format); } } @Command(name = "artifact", mixinStandardHelpOptions = true, description = "Attach small evidence files with integrity metadata.") public class ArtifactCommands { @Command(name = "add", mixinStandardHelpOptions = true) int add(@Parameters(index = "0") String id, @Option(names = "--file", required = true) Path file, @Option(names = "--purpose", required = true) String purpose, @Option(names = "--origin") String origin, @Option(names = "--author", defaultValue = "human") String author) { return emit(new ArtifactService().attach(root(), id, resolve(file), purpose, origin, author), Format.markdown); } } public static class DiscussionText { @Option(names = "--text", description = "Inline discussion text.") String text; @Option(names = "--text-file", description = "Read the complete UTF-8 file (up to 1 MiB), relative to the current directory.") Path file; } private String optionalText(String text, Path file) { if (text != null && file != null) throw ProtocolException.invalid("Use --text or --text-file, not both"); return file == null ? text : readDiscussionText(resolve(file)); } private static List replacement(List values, boolean clear) { if (values != null && clear) throw ProtocolException.invalid("Specify replacement values or the corresponding --clear option"); return clear ? List.of() : values; } private static String readDiscussionText(Path path) { if (!Files.exists(path)) throw ProtocolException.missing("Missing discussion text file: " + path); if (!Files.isRegularFile(path)) throw ProtocolException.invalid("Discussion text source must be a regular file: " + path); int maxBytes = 1024 * 1024; byte[] bytes = Filespace.io(() -> { try (var input = Files.newInputStream(path)) { return input.readNBytes(maxBytes + 1); } }); if (bytes.length > maxBytes) throw ProtocolException.invalid("Discussion text file exceeds 1 MiB: " + path); try { String text = java.nio.charset.StandardCharsets.UTF_8.newDecoder() .decode(java.nio.ByteBuffer.wrap(bytes)).toString(); return ProtocolException.text(text, "discussion text"); } catch (java.nio.charset.CharacterCodingException e) { throw ProtocolException.invalid("Discussion text file must use UTF-8: " + path); } } private static List safe(List list) { return list == null ? List.of() : list; } }