diff --git a/README.md b/README.md index 2d51057..3b61b2a 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ State stays outside Git by default. Versioning it is the developer's choice. consolidate completed plans through deterministic checks. - **Coordinate repositories:** explicitly select the repositories involved in each Work, while keeping engineering records in one project. +- **Capture cross-project requests:** record text in another local project's inbox + even with its server stopped, then discuss and incorporate it into a Work. - **Work with AI agents:** provide portable entry instructions and structured context; optionally use local Codex or Claude CLIs for proposals and summaries. - **Retain history:** read supported older formats without rewriting completed @@ -132,7 +134,8 @@ address next. Every command provides `--help`; inspection commands support JSON. ### Manage the local server -Ordinary commands start the project's server when needed. To control its lifetime: +Ordinary commands start the project's server when needed. `request create` writes +directly to the destination inbox without starting a server. To control its lifetime: ```sh aie start # Start or reuse; wait until ready @@ -315,6 +318,7 @@ Tests generate JUnit results and JaCoCo coverage. Open | [Storage migration](docs/storage-migration.md) | Preview, apply, recover and rollback | | [Work conduct and OODA](docs/work-guidance.md) | Human discussion choices, DEC authority and optional Plan experiments | | [Discussion and refinement](docs/discussion-slice.md) | Topics, surveys, and proposal handling | +| [Local Requests](docs/requests.md) | Capture text without a server and incorporate it into Work context | | [Plan consolidation](docs/plan-consolidation.md) | Steps, results, and automatic completion | | [EPIC coordination](docs/epics.md) | Relationships and completion policies across Works | | [Local CLI adapters](docs/cli-adapters.md) | Provider setup and invocation contract | diff --git a/docs/architecture.md b/docs/architecture.md index 0c69b45..823ea47 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -39,6 +39,7 @@ POST operations. See [event protocol](local-server-sse.md). | artifact | Temporary payloads, lifecycle, publication recovery and typed receipts | work, filesystem | | agent | Proposal adapters, bounded local transport, validation and application | project, work, discussion, decision, planning, artifact, filesystem | | legacyimport | Explicit DF preview/import, preserved originals and provenance | filesystem, project, work, discussion, artifact | +| request | Offline textual inbox and recoverable incorporation into Work discussion context | filesystem, project, work, discussion | | verification | Integrity/readiness, gates, snapshots, coordination, migration and context | protocol modules | | cli | Picocli commands and presentation | public module APIs | | localserver | Private process identity/locks, HTTP client/server, invocation jobs, durable outcomes | cli, filesystem, project | @@ -77,6 +78,15 @@ waiting. Ordinary related reads need no file lock and use one database snapshot. ## Quality and temporary files +Pending cross-project Requests are Markdown files in `.ai-engineering/requests/`. +Only `request create` bypasses the server and SQL, using independent UUIDs and atomic +file publication. Treatment uses the normal server command path. Incorporation +records original text and provenance in an ordinary discussion NOTE with a stable +`request:REQ-...` thread; it adds no storage table or Work field. SQL commit precedes +cleanup; a deterministic claimed filename supports recovery after a crash. Repeated +incorporation reuses the existing note and rejects changed input or another Work. +See [Requests](requests.md). + QualityGates stores required project definitions and cumulative Work additions. Observed results bind procedures, actual invocation, inputs, Work scope/guidance, DEC revisions, outcome and a short summary. Missing, failed or stale gates block diff --git a/docs/local-server.md b/docs/local-server.md index 198e9a8..f1429c6 100644 --- a/docs/local-server.md +++ b/docs/local-server.md @@ -10,7 +10,10 @@ distribution default; the same entry point supports a JVM for development. drains admitted operations and is successful when already stopped. Normal commands can start the server again. Idle servers stop after 30 minutes with no active jobs; the timeout is configurable. Help, version, initialization and bootstrap guidance -do not need a server. `aie status` retains its existing project-status meaning. +do not need a server. `request create` also runs directly in the client and writes +only a textual file to the destination inbox. `request list/show/incorporate` use +the server for explicit treatment; see [Requests](requests.md). +`aie status` retains its existing project-status meaning. The canonical project path owns an exclusive OS lock and a loopback-only ephemeral port. A private descriptor under `.ai-engineering/.local/server/` contains the diff --git a/docs/protocol.md b/docs/protocol.md index 071ae2c..296be88 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -3,7 +3,9 @@ AIE is a local framework per project. `.ai-engineering/aie.db` owns operational memory: Works, investigation, decisions, Plans, execution facts and gate results. Small YAML/JSON and README/AGENTS files bootstrap discovery and configuration. -There is no database server or background process. Git and source repositories are +There is no separately managed database service; the CLI starts and reuses a local +project server. Pending cross-project Requests are text files outside SQL, and their +creation works with the server stopped. Git and source repositories are optional; synchronization, distributed IDs, Git LFS and Work/DEC export are outside this version. @@ -25,6 +27,14 @@ new identities and owned references together. Migration preserves reserved gaps. ## Investigation and implementation +`request create TITLE --project DEST --author NAME --text TEXT` records a Request +directly in the local destination's `.ai-engineering/requests/` without SQL or a +server. Use `--text-file PATH` for multiline source text and optional +`--source-work WRK-ID` for provenance. `request list/show/incorporate` use the server +for explicit treatment with the human and current AI. Incorporation preserves the +full original in Work context before removing the file; retries are idempotent. +Attachments are deferred. See [Requests](requests.md) for commands and recovery. + Discussion/investigation and implementation remain separate cycles connected by DEC and Plan. Work stores scope, criteria and useful refinement; topics, surveys, answer supersession and explicit conclusions preserve continuity. OODA is adaptive: diff --git a/docs/requests.md b/docs/requests.md new file mode 100644 index 0000000..1449f36 --- /dev/null +++ b/docs/requests.md @@ -0,0 +1,103 @@ +# Requests between local projects + +A Request records a textual demand from one local AIE project for another. Capture +works with both servers stopped. It writes one Markdown UTF-8 file to the destination's +`.ai-engineering/requests/`, without opening SQL, starting a server or looking for +similar requests. An existing project configuration and write access are required. + +## Capture + +From the source project (or one of its subdirectories): + +```sh +aie request create "Expose the new parser API" \ + --project /path/to/destination --author source-agent \ + --source-work WRK-000F --text "The source project needs the parser diagnostics." +``` + +`--project` is the required, explicit destination, not the source. It also accepts +the destination's `.ai-engineering` directory. The source project is discovered +from the caller's current directory. `--source-project /path/to/source` overrides +that discovery; `--source-work` is optional and records a reference without querying +the source's memory. Specify the actual human or agent with `--author`. + +Use exactly one of `--text TEXT` or `--text-file PATH`. Input file paths are relative +to the caller's current directory. The body preserves Unicode, indentation, blank +lines and trailing newlines. Text must be nonblank; the complete stored document is +limited to 1 MiB. Attachments are deferred. + +Creation returns the Request and its absolute file path. `--format json` provides +structured output. Files use `REQ-.md`, with YAML front matter for schema and +document versions, ID, title, source project, author, creation date and optional +source Work. The body contains the original text. There is no shared counter. +Publication makes a complete file visible atomically and cannot overwrite another +producer's Request. SQL/bootstrap operational records are unchanged. + +## Discuss and incorporate + +At the destination, or with its path supplied through `--project`: + +```sh +aie request list +aie request show REQ-00000000-0000-0000-0000-000000000001 +``` + +These commands use the destination server, starting it through the normal client +flow if needed. The human and current AI discuss and group the texts in their +ordinary conversation. Nothing analyzes or groups them automatically. + +Choose an existing Work or create one using the normal Work commands, with the +human's discussion mode and the usual decision authority. Then incorporate each +selected Request explicitly: + +```sh +aie request incorporate REQ-00000000-0000-0000-0000-000000000001 \ + --work WRK-0001 --by destination-agent +aie work context WRK-0001 +``` + +The original text and provenance become a NOTE in the Work's discussion history, +under the thread `request:REQ-...`. Provenance includes the title, origin, original +author/date, optional source Work and SHA-256 of the captured document. The note's +author identifies the handler supplied through `--by`. A later synthesis may +complement this note. The full original remains available in Work context after +the Request file is removed; no second collection of treated files is retained. + +Multiple Requests can be incorporated into the same Work. A Request already +incorporated into another Work is a conflict. Incorporation does not transfer +source approvals or authorize implementation. + +## Failure and retry + +The Work context commits before file deletion. On SQLite, the note and Work +reference share a transaction; an enclosing rollback leaves the input untouched. +If persistence fails, the Request remains available. After persistence, cleanup +claims the file as `.REQ-.consuming.md` before checking and removing it. A +crash leaves this deterministic file discoverable by `request list` and `show`. + +Repeat `request incorporate` with the same Request ID and Work after interrupted +cleanup. The recorded thread, text and document hash identify the existing context; +the operation finishes cleanup without adding a second note. Repeating after +successful deletion also returns the previous incorporation with `reused: true`. +Changed input or a different destination Work is reported as a conflict, retaining +the remaining file for review. Both a normal file and a recovery file for one ID +require explicit inspection; neither is silently overwritten. Reads do not remove +files or perform recovery. + +Pending Requests remain filesystem inputs rather than SQL records. Incorporation +uses ordinary Work discussion storage, including SQL on SQLite projects, without +adding a Request table or changing the database schema. The supported legacy +backend retains its normal per-file persistence limits. + +## Native verification + +After building the candidate with `./gradlew nativePackage`, run: + +```sh +python3 scripts/native-requests-smoke.py --binary build/native/package/ai-engineering +``` + +This creates disposable source/destination projects, checks offline capture leaves +the database and server state untouched, incorporates two Requests through the +native server, verifies original context and retry behavior, and stops its servers. +The full package verifier also runs this scenario. diff --git a/scripts/native-requests-smoke.py b/scripts/native-requests-smoke.py new file mode 100644 index 0000000..d1c9285 --- /dev/null +++ b/scripts/native-requests-smoke.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Exercise offline capture and server incorporation using disposable native projects.""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + args = parser.parse_args() + binary = args.binary.resolve() + + with tempfile.TemporaryDirectory(prefix="aie-native-requests-") as temporary: + base = Path(temporary).resolve() + source, destination = base / "source", base / "destination" + source.mkdir() + destination.mkdir() + + def run(cwd, *argv, expected=0): + result = subprocess.run([str(binary), *argv], cwd=cwd, text=True, + capture_output=True, timeout=25) + if result.returncode != expected: + raise AssertionError(f"Command {argv!r}: exit {result.returncode}\n{result.stderr}\n{result.stdout}") + return result.stdout + + def command(*argv): + return run(destination, *argv) + + try: + run(source, "init", "--name", "Request producer") + command("init", "--name", "Request consumer") + nested = source / "nested" + nested.mkdir() + original = "\nUnicode é 请求\n\n---\n indentation\n" + (nested / "text.txt").write_text(original, encoding="utf-8") + database = destination / ".ai-engineering/aie.db" + before = hashlib.sha256(database.read_bytes()).hexdigest() + created = json.loads(run(nested, "request", "create", "Parser API", "--project", str(destination), + "--author", "source-agent", "--source-work", "WRK-000A", + "--text-file", "text.txt", "--format", "json")) + second = json.loads(run(source, "--project", str(destination), "request", "create", "Follow-up", + "--author", "source-agent", "--text", "Inline request", "--format", "json")) + assert created["request"]["text"] == original + assert created["request"]["sourceProject"] == str(source) + assert created["request"]["sourceWork"] == "WRK-000A" + assert hashlib.sha256(database.read_bytes()).hexdigest() == before + for project in (source, destination): + assert not (project / ".ai-engineering/.local/server").exists(), "Capture started a server" + + command("work", "create", "Handle parser Requests", "--mode", "EXPLORATORY", "--author", "smoke", + "--choice-reason", "Explicit disposable smoke fixture", "--human-approved") + pending = json.loads(command("request", "list", "--format", "json")) + assert len(pending) == 2 + identifier = created["request"]["id"] + assert json.loads(command("request", "show", identifier, "--format", "json"))["text"] == original + for captured in (created, second): + result = json.loads(command("request", "incorporate", captured["request"]["id"], + "--work", "WRK-0001", "--by", "destination-agent", "--format", "json")) + assert result["reused"] is False + assert not Path(captured["path"]).exists() + repeated = json.loads(command("request", "incorporate", identifier, + "--work", "WRK-0001", "--by", "destination-agent", "--format", "json")) + assert repeated["reused"] is True + context = json.loads(command("work", "context", "WRK-0001", "--format", "json")) + assert len(context["discussionHistory"]) == 2 + notes = {note["discussionId"]: note for note in context["discussionHistory"]} + assert notes["request:" + identifier]["text"].endswith(original) + assert notes["request:" + identifier]["author"] == "destination-agent" + assert json.loads(command("request", "list", "--format", "json")) == [] + assert json.loads(command("work", "validate", "WRK-0001", "--format", "json"))["valid"] is True + assert not (source / ".ai-engineering/.local/server").exists() + print(json.dumps({"requests": 2, "contextEntries": 2, "offlineDatabaseUnchanged": True, + "retryReused": True, "validation": "PASS"})) + finally: + for project in (destination, source): + if (project / ".ai-engineering/.local/server/endpoint.json").exists(): + run(project, "stop", "--timeout-seconds", "10") + + +if __name__ == "__main__": + main() diff --git a/scripts/verify-native-package.py b/scripts/verify-native-package.py index 6c1c375..991ae4c 100644 --- a/scripts/verify-native-package.py +++ b/scripts/verify-native-package.py @@ -65,6 +65,8 @@ with tempfile.TemporaryDirectory(prefix="aie-package-check-") as temporary: subprocess.run([str(aie), "stop", "--timeout-seconds", "10"], cwd=root, check=True, stdout=subprocess.DEVNULL, timeout=15) if manifest.get("localServerEvents") == "sse": + subprocess.run([sys.executable, str(Path(__file__).with_name("native-requests-smoke.py")), + "--binary", str(aie)], check=True, timeout=120) subprocess.run([sys.executable, str(Path(__file__).with_name("native-sse-smoke.py")), "--binary", str(aie)], check=True, timeout=120) print("Native package verified:", package) diff --git a/src/main/java/net/intrepid/aiengineering/NativeHints.java b/src/main/java/net/intrepid/aiengineering/NativeHints.java index 459e926..573f96d 100644 --- a/src/main/java/net/intrepid/aiengineering/NativeHints.java +++ b/src/main/java/net/intrepid/aiengineering/NativeHints.java @@ -12,6 +12,7 @@ import net.intrepid.aiengineering.verification.*; import net.intrepid.aiengineering.legacyimport.DiscussionImport; import org.springframework.aot.hint.*; import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.request.*; public final class NativeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader loader) { @@ -47,7 +48,8 @@ public final class NativeHints implements RuntimeHintsRegistrar { DiscussionImport.Entry.class, DiscussionImport.Report.class, DiscussionImport.ImportedAgenda.class, DiscussionImport.Receipt.class, DiscussionImport.Action.class, Artifact.class, ProtocolReceipt.class, ProtocolReceipt.Source.class, ArtifactPublication.Intent.class, - ValidationReport.class, VerificationService.Context.class, DiscussionService.MigrationReport.class}) { + ValidationReport.class, VerificationService.Context.class, DiscussionService.MigrationReport.class, + ProjectRequest.class, RequestService.Created.class, RequestService.Incorporated.class}) { hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS); } hints.resources().registerPattern("protocol/*"); diff --git a/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java b/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java index b621287..9dddc50 100644 --- a/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java +++ b/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java @@ -9,6 +9,7 @@ import net.intrepid.aiengineering.artifact.*; import net.intrepid.aiengineering.planning.*; import net.intrepid.aiengineering.agent.*; import net.intrepid.aiengineering.verification.*; +import net.intrepid.aiengineering.request.RequestService; import picocli.CommandLine; import picocli.CommandLine.*; import java.io.PrintWriter; @@ -86,7 +87,8 @@ public final class EngineeringCli implements Runnable { case "discussion" -> new DiscussionCommands(); case "decision" -> new DecisionCommands(); case "artifact" -> new ArtifactCommands(); case "plan" -> new PlanCommands(); case "topic" -> new TopicCommands(); case "survey" -> new SurveyCommands(); case "agent" -> new AgentCommands(); case "epic" -> new EpicCommands(); case "gate" -> new GateCommands(); - case "storage" -> new StorageCommands(); case "import" -> new ImportCommands(); default -> null; + case "storage" -> new StorageCommands(); case "import" -> new ImportCommands(); + case "request" -> new RequestCommands(); default -> null; }; if (owner instanceof PlanCommands) return switch(name) { case "step" -> new StepCommands(); case "experiment" -> new ExperimentCommands(); default -> null; @@ -105,7 +107,8 @@ public final class EngineeringCli implements Runnable { .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()).addSubcommand("gate", new GateCommands()).addSubcommand("storage", new StorageCommands()); + .addSubcommand("epic", new EpicCommands()).addSubcommand("gate", new GateCommands()).addSubcommand("storage", new StorageCommands()) + .addSubcommand("request", new RequestCommands()); commandLine.addSubcommand("import", new CommandLine(new ImportCommands()).addSubcommand("discussion", new DiscussionImportCommand())); configureExecution(commandLine,out,err); return commandLine; @@ -130,6 +133,42 @@ public final class EngineeringCli implements Runnable { } private Path resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); } enum Format { markdown, json } + @Command(name = "request", mixinStandardHelpOptions = true, + description = "Capture local textual Requests offline and incorporate them into Works with the server.") + public class RequestCommands { + @Command(name = "create", mixinStandardHelpOptions = true, + description = "Write a Request directly to --project, without starting a server or opening SQL.") + int create(@Parameters(index = "0") String title, + @ArgGroup(exclusive = true, multiplicity = "1") RequestText input, + @Option(names = "--author", required = true) String author, + @Option(names = "--source-project", description = "Source project path; default is discovered from the current directory.") Path source, + @Option(names = "--source-work") String sourceWork, + @Option(names = "--format", defaultValue = "markdown") Format format) { + if (project == null) throw ProtocolException.invalid("Request creation requires explicit --project for the destination"); + Path destination = discoveredRoot(); + String text = input.text != null ? input.text : readText(resolve(input.file), "Request"); + return emit(new RequestService().create(destination, source == null ? cwd : resolve(source), title, text, author, sourceWork), format); + } + @Command(name = "list", mixinStandardHelpOptions = true, description = "List pending Requests, including interrupted cleanup, through the server.") + int list(@Option(names = "--format", defaultValue = "markdown") Format format) { + return emit(new RequestService().list(root()), format); + } + @Command(name = "show", mixinStandardHelpOptions = true) + int show(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { + var request = new RequestService().show(root(), id); + if (format == Format.json) return emit(request, format); + output.print(Documents.markdownDocument(request, "text")); return 0; + } + @Command(name = "incorporate", mixinStandardHelpOptions = true, + description = "Persist the original Request in --work context, then remove its file; retries are idempotent.") + int incorporate(@Parameters(index = "0") String id, + @Option(names = "--work", required = true) String work, + @Option(names = "--by", required = true) String by, + @Option(names = "--format", defaultValue = "markdown") Format format) { + var result = new RequestService().incorporate(root(), id, work, by); + emit(result, format); afterChange(work, by); return 0; + } + } @Command(name = "storage", mixinStandardHelpOptions = true, description = "Explicit local storage migration and recovery; never installs native tools.") public class StorageCommands { @Command(name = "migrate", mixinStandardHelpOptions = true, description = "Preview by default. Apply, recover or roll back using the reviewed fingerprint.") @@ -832,20 +871,27 @@ public final class EngineeringCli implements Runnable { if (values != null && clear) throw ProtocolException.invalid("Specify replacement values or the corresponding --clear option"); return clear ? List.of() : values; } + static class RequestText { + @Option(names = "--text") String text; + @Option(names = "--text-file", description = "UTF-8 Request text, relative to the current directory (up to 1 MiB).") Path file; + } 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); + return readText(path, "Discussion"); + } + private static String readText(Path path, String subject) { + if (!Files.exists(path)) throw ProtocolException.missing("Missing " + subject.toLowerCase(java.util.Locale.ROOT) + " text file: " + path); + if (!Files.isRegularFile(path)) throw ProtocolException.invalid(subject + " 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); + if (bytes.length > maxBytes) throw ProtocolException.invalid(subject + " 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"); + return ProtocolException.text(text, subject.toLowerCase(java.util.Locale.ROOT) + " text"); } catch (java.nio.charset.CharacterCodingException e) { - throw ProtocolException.invalid("Discussion text file must use UTF-8: " + path); + throw ProtocolException.invalid(subject + " text file must use UTF-8: " + path); } } private static List safe(List list) { return list == null ? List.of() : list; } diff --git a/src/main/java/net/intrepid/aiengineering/cli/package-info.java b/src/main/java/net/intrepid/aiengineering/cli/package-info.java index a13cfc1..b848ed9 100644 --- a/src/main/java/net/intrepid/aiengineering/cli/package-info.java +++ b/src/main/java/net/intrepid/aiengineering/cli/package-info.java @@ -1,2 +1,2 @@ -@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact", "verification", "planning", "agent", "legacyimport"}) +@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact", "verification", "planning", "agent", "legacyimport", "request"}) package net.intrepid.aiengineering.cli; diff --git a/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java b/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java index ed931a5..aaaec54 100644 --- a/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java +++ b/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java @@ -6,14 +6,15 @@ import java.util.*; /** Routing comes from the actual Picocli parse, never from scanning option values for keywords. */ public final class InvocationPolicy { private InvocationPolicy() {} - private static final Set LOCAL = Set.of("init", "guide", "agent list", "agent doctor"); + private static final Set LOCAL = Set.of("init", "guide", "agent list", "agent doctor", "request create"); private static final Set READS = Set.of( "status", "next-actions", "project show", "project validate", "project compatibility", "repo list", "work show", "work list", "work context", "work check", "work validate", "discussion list", "discussion show", "decision list", "decision show", "decision history", "plan list", "plan show", "plan history", "plan experiment list", "plan experiment show", "artifact list", "topic list", "topic show", "survey list", "survey show", "survey history", - "agent show", "agent history", "epic show", "epic check", "epic history", "gate status", "gate history"); + "agent show", "agent history", "epic show", "epic check", "epic history", "gate status", "gate history", + "request list", "request show"); public static String path(CommandLine.ParseResult parse) { var parts = new ArrayList(); for (var child = parse.subcommand(); child != null; child = child.subcommand()) diff --git a/src/main/java/net/intrepid/aiengineering/request/ProjectRequest.java b/src/main/java/net/intrepid/aiengineering/request/ProjectRequest.java new file mode 100644 index 0000000..e0bb7a7 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/request/ProjectRequest.java @@ -0,0 +1,24 @@ +package net.intrepid.aiengineering.request; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import net.intrepid.aiengineering.work.Work; +import java.time.Instant; + +/** A pending, textual request; deliberately independent of Work/SQL storage. */ +public record ProjectRequest(int schemaVersion, String id, String title, String sourceProject, + String author, String createdAt, String sourceWork, String text) { + public ProjectRequest { + ProtocolException.schema(schemaVersion); identifier(id); + ProtocolException.text(title, "request title"); + ProtocolException.text(sourceProject, "request source project"); + ProtocolException.text(author, "request author"); + ProtocolException.text(text, "request text"); + if (createdAt == null) throw ProtocolException.invalid("Missing request creation date"); + Instant.parse(createdAt); + if (sourceWork != null) Work.identifier(sourceWork, "WRK"); + } + public static void identifier(String id) { + if (id == null || !id.matches("REQ-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) + throw ProtocolException.invalid("Invalid Request ID: " + id); + } +} diff --git a/src/main/java/net/intrepid/aiengineering/request/RequestService.java b/src/main/java/net/intrepid/aiengineering/request/RequestService.java new file mode 100644 index 0000000..555388b --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/request/RequestService.java @@ -0,0 +1,142 @@ +package net.intrepid.aiengineering.request; + +import net.intrepid.aiengineering.discussion.*; +import net.intrepid.aiengineering.filesystem.*; +import net.intrepid.aiengineering.project.ProjectService; +import net.intrepid.aiengineering.project.ProtocolGuide; +import net.intrepid.aiengineering.work.WorkService; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.time.Instant; +import java.util.*; +import java.util.function.Consumer; +import static java.nio.file.LinkOption.NOFOLLOW_LINKS; + +/** Capture touches only bootstrap files and the inbox. Treatment runs on the project server. */ +public final class RequestService { + private static final int MAX_BYTES = 1024 * 1024; + private final WorkService works = new WorkService(); + private final DiscussionService discussions = new DiscussionService(); + private final Consumer beforeDelete; + public RequestService() { this(path -> {}); } + // Fault boundary after persistence and claim, before deletion, for recovery tests. + RequestService(Consumer beforeDelete) { this.beforeDelete = beforeDelete; } + public record Created(ProjectRequest request, String path) {} + public record Incorporated(String requestId, String workId, String discussionId, boolean reused) {} + private record Snapshot(ProjectRequest request, String raw) {} + + private Path inbox(Path root) { return Filespace.resolve(root, ".ai-engineering/requests"); } + private Path pending(Path root, String id) { + ProjectRequest.identifier(id); return Filespace.resolve(inbox(root), id + ".md"); + } + private Path claimed(Path root, String id) { + ProjectRequest.identifier(id); return Filespace.resolve(inbox(root), "." + id + ".consuming.md"); + } + public Created create(Path destination, Path source, String title, String text, String author, String sourceWork) { + var projects = new ProjectService(); + Path root = projects.discover(destination, destination); + Path origin = projects.discover(source, null); + projects.load(root); projects.load(origin); // Bootstrap only; never select/open a database here. + ProtocolGuide.requireSupportedVersion(root); ProtocolGuide.requireSupportedVersion(origin); + var request = new ProjectRequest(1, "REQ-" + UUID.randomUUID(), title, origin.toString(), + author, Instant.now().toString(), sourceWork, text); + String raw = Documents.markdownDocument(request, "text"); + if (raw.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) + throw ProtocolException.invalid("Request document exceeds 1 MiB"); + Path path = pending(root, request.id()); Filespace.directory(path.getParent()); + Filespace.write(path, raw, false); + return new Created(request, path.toString()); + } + public List list(Path root) { + Path directory = inbox(root); + if (!Files.exists(directory, NOFOLLOW_LINKS)) return List.of(); + var ids = new TreeSet(); + for (Path child : Filespace.io(() -> { try (var stream = Files.list(directory)) { return stream.toList(); } })) { + String name = child.getFileName().toString(); + if (name.startsWith("REQ-") && name.endsWith(".md")) ids.add(name.substring(0, name.length() - 3)); + else if (name.startsWith(".REQ-") && name.endsWith(".consuming.md")) + ids.add(name.substring(1, name.length() - ".consuming.md".length())); + } + return ids.stream().map(id -> show(root, id)).toList(); + } + public ProjectRequest show(Path root, String id) { return snapshot(root, id).request(); } + private Snapshot snapshot(Path root, String id) { + Path normal = pending(root, id), recovery = claimed(root, id); + if (Files.exists(normal, NOFOLLOW_LINKS) && Files.exists(recovery, NOFOLLOW_LINKS)) + throw ProtocolException.validation("Request has pending and recovery files; inspect both before retrying: " + id); + Path path = Files.exists(normal, NOFOLLOW_LINKS) ? normal : recovery; + String raw = read(path); + var request = Documents.parseMarkdownDocument(raw, ProjectRequest.class, "text"); + if (!request.id().equals(id)) throw ProtocolException.validation("Request filename/identity mismatch: " + id); + return new Snapshot(request, raw); + } + private String read(Path path) { + // Recheck all components when recovering a claimed file as well. + Filespace.resolve(path.getParent(), path.getFileName().toString()); + if (!Files.exists(path, NOFOLLOW_LINKS)) throw ProtocolException.missing("Request file not found: " + path); + if (!Files.isRegularFile(path, NOFOLLOW_LINKS)) throw ProtocolException.invalid("Request must be a regular file: " + path); + byte[] bytes = Filespace.io(() -> { try (var input = Files.newInputStream(path, NOFOLLOW_LINKS)) { return input.readNBytes(MAX_BYTES + 1); } }); + if (bytes.length > MAX_BYTES) throw ProtocolException.invalid("Request document exceeds 1 MiB: " + path); + try { return StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); } + catch (java.nio.charset.CharacterCodingException invalid) { throw ProtocolException.invalid("Request must use UTF-8: " + path); } + } + private String thread(String id) { return "request:" + id; } + /** Human-readable provenance, not a serialized copy of the input document. */ + private String context(Snapshot snapshot) { + var r = snapshot.request(); + return "# Request " + r.id() + "\n\n" + + "Title: " + r.title() + "\nSource project: " + r.sourceProject() + + "\nAuthor: " + r.author() + "\nCreated: " + r.createdAt() + + "\nSource Work: " + (r.sourceWork() == null ? "(none)" : r.sourceWork()) + + "\nSource SHA-256: " + Revisions.hash(snapshot.raw()) + + "\n\nOriginal request text:\n\n" + r.text(); + } + private DiscussionEntry incorporated(Path root, String id) { + var matches = works.list(root).stream().flatMap(w -> discussions.list(root, w.id()).stream()) + .filter(e -> e.discussionId().equals(thread(id))).toList(); + if (matches.size() > 1) throw ProtocolException.validation("Request was incorporated more than once; inspect context: " + id); + return matches.isEmpty() ? null : matches.getFirst(); + } + public Incorporated incorporate(Path root, String id, String work, String by) { + ProjectRequest.identifier(id); net.intrepid.aiengineering.work.Work.identifier(work, "WRK"); + ProtocolException.text(by, "request handler"); + return Filespace.locked(root, () -> { + var prior = incorporated(root, id); + if (prior != null && !prior.workId().equals(work)) + throw ProtocolException.validation("Request already belongs to " + prior.workId() + ": " + id); + if (!Files.exists(pending(root, id), NOFOLLOW_LINKS) && !Files.exists(claimed(root, id), NOFOLLOW_LINKS)) { + if (prior == null) throw ProtocolException.missing("Request not found: " + id); + return new Incorporated(id, work, prior.id(), true); + } + var snapshot = snapshot(root, id); + String text = context(snapshot); + if (prior != null && !prior.text().equals(text)) + throw ProtocolException.validation("Request conflicts with incorporated content; file retained: " + id); + var entry = prior != null ? prior : discussions.add(root, work, text, DiscussionEntry.Kind.NOTE, by, thread(id), null); + Runnable cleanup = () -> cleanup(root, snapshot); + // A nested caller's SQL transaction must commit before any deletion. + if (SqliteDatabase.active(root)) SqliteDatabase.afterCommit(root, cleanup); + else cleanup.run(); + return new Incorporated(id, work, entry.id(), prior != null); + }); + } + private void cleanup(Path root, Snapshot snapshot) { + String id = snapshot.request().id(); + Path normal = pending(root, id), recovery = claimed(root, id); + if (!Files.exists(recovery, NOFOLLOW_LINKS)) Filespace.io(() -> { + Files.move(normal, recovery, StandardCopyOption.ATOMIC_MOVE); return null; + }); + // A crash here leaves a deterministic recovery file, discoverable by list/show/incorporate. + beforeDelete.accept(recovery); + if (!read(recovery).equals(snapshot.raw())) { + // Restore without overwriting a concurrently published replacement. Never discard changed input. + if (!Files.exists(normal, NOFOLLOW_LINKS)) Filespace.io(() -> { + Files.createLink(normal, recovery); Files.delete(recovery); return null; + }); + throw ProtocolException.validation("Request changed after incorporation; file retained for review: " + id); + } + Filespace.io(() -> { Files.delete(recovery); return null; }); + if (Files.exists(normal, NOFOLLOW_LINKS)) + throw ProtocolException.validation("A replacement Request file remains; inspect before retrying: " + id); + } +} diff --git a/src/main/java/net/intrepid/aiengineering/request/package-info.java b/src/main/java/net/intrepid/aiengineering/request/package-info.java new file mode 100644 index 0000000..f828035 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/request/package-info.java @@ -0,0 +1,2 @@ +@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion"}) +package net.intrepid.aiengineering.request; diff --git a/src/main/resources/protocol/README.md b/src/main/resources/protocol/README.md index 2f33c57..2ad5c2e 100644 --- a/src/main/resources/protocol/README.md +++ b/src/main/resources/protocol/README.md @@ -121,6 +121,31 @@ Works to materialize new fields. Inspect compatibility and onboard before adopti ## Topics, surveys and refinement +### Requests from other local projects + +`request create TITLE --project DEST --author NAME --text TEXT` writes a Request +directly to DEST's `.ai-engineering/requests/`, without consulting/starting a server, +opening SQL or checking similarity. Use `--text-file PATH` instead of `--text` for +UTF-8 input (the complete stored document is limited to 1 MiB). DEST must already be +an AIE project. Source discovery uses the caller's current directory; override with +`--source-project PATH`. `--source-work WRK-ID` is an optional provenance reference. +Each Request has a UUID, original text and YAML metadata in a Markdown file. + +`request list` and `request show REQ-ID` use the destination server. Discuss and +group the Requests with the human and current AI using the normal conversation. +Create a Work through the ordinary guided flow, or select an existing Work, then +run `request incorporate REQ-ID --work WRK-ID --by NAME`. This persists the full +text and origin as a discussion NOTE in Work context before removing the file. +An additional synthesis may complement the original. Requests do not carry approval +or authorize execution. Attachments and automatic triage are deferred. + +Repeat incorporation with the same ID/Work after a failure: it recognizes existing +context and completes cleanup without duplication. Interrupted cleanup files named +`.REQ-.consuming.md` remain discoverable through list/show. Changed content, +a different Work, or simultaneous pending/recovery files require inspection and +remain retained. Reads do not perform cleanup. Pending Requests remain files; +incorporated context uses the normal Work storage without a new Request table. + Discussion remains the refinement space: receive ideas, organize topics, investigate, record results and prepare decisions. Use `topic create/list/show/update` to organize formal topics; legacy discussion threads appear as implicit topics without rewriting diff --git a/src/test/java/net/intrepid/aiengineering/LocalRequestTest.java b/src/test/java/net/intrepid/aiengineering/LocalRequestTest.java new file mode 100644 index 0000000..a315637 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/LocalRequestTest.java @@ -0,0 +1,75 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.cli.EngineeringCli; +import net.intrepid.aiengineering.filesystem.*; +import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.project.ProjectService; +import net.intrepid.aiengineering.request.*; +import net.intrepid.aiengineering.work.WorkService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import static org.assertj.core.api.Assertions.*; + +class LocalRequestTest { + @TempDir Path temporary; + private record Result(int code, String out, String err) {} + private Result cli(Path cwd, String... args) { + var out = new StringWriter(); var err = new StringWriter(); + int code = new LocalClient(cwd, new StringReader(""), new PrintWriter(out), new PrintWriter(err), false).execute(args); + return new Result(code, out.toString(), err.toString()); + } + @Test void publicClientCapturesOfflineFromNestedCwdAndServerIncorporatesIntoNormalContext() throws Exception { + Path source = Files.createDirectory(temporary.resolve("source")).toRealPath(); + Path destination = Files.createDirectory(temporary.resolve("destination")).toRealPath(); + new ProjectService().initializeSqlite(source, "Source"); new ProjectService().initializeSqlite(destination, "Destination"); + Path cwd = Files.createDirectories(source.resolve("nested/deep")); + String text = "\nUnicode é 请求\n\n---\nexact trailing newline\n"; + Files.writeString(cwd.resolve("note.txt"), text); + byte[] database = Files.readAllBytes(destination.resolve(".ai-engineering/aie.db")); + var captured = cli(cwd, "request", "create", "Text request", "--project", destination.toString(), "--author", "agent", "--text-file", "note.txt", "--format", "json"); + assertThat(captured.code()).as(captured.err()).isZero(); + var created = Documents.parseJson(captured.out(), RequestService.Created.class); + assertThat(created.request().text()).isEqualTo(text); + assertThat(created.request().sourceProject()).isEqualTo(source.toString()); + assertThat(created.request().sourceWork()).isNull(); + assertThat(Files.readAllBytes(destination.resolve(".ai-engineering/aie.db"))).isEqualTo(database); + assertThat(source.resolve(".ai-engineering/.local/server")).doesNotExist(); + assertThat(destination.resolve(".ai-engineering/.local/server")).doesNotExist(); + var work = new WorkService().create(destination, "New Work", "", "", "", List.of(), List.of(), List.of(), "tester"); + // Real server transport, while keeping this fixture server inside the test JVM. + try (var server = new ProjectServer(new ServerState(destination), 60000, new RequestJobs(new ServerState(destination)))) { + var list = cli(source, "--project", destination.toString(), "request", "list", "--format", "json"); + assertThat(list.code()).as(list.err()).isZero(); assertThat(list.out()).contains(created.request().id()); + var show = cli(source, "request", "show", created.request().id(), "--project", destination.toString()); + assertThat(show.code()).as(show.err()).isZero(); assertThat(show.out()).endsWith(text); + var result = cli(source, "request", "incorporate", created.request().id(), "--project", destination.toString(), "--work", work.id(), "--by", "handler"); + assertThat(result.code()).as(result.err()).isZero(); assertThat(Path.of(created.path())).doesNotExist(); + var context = cli(source, "work", "context", work.id(), "--project", destination.toString()); + assertThat(context.code()).as(context.err()).isZero(); assertThat(context.out()).contains(text, created.request().id()); + var repeated = cli(source, "request", "incorporate", created.request().id(), "--project", destination.toString(), "--work", work.id(), "--by", "handler"); + assertThat(repeated.code()).as(repeated.err()).isZero(); assertThat(repeated.out()).contains("reused: true"); + } + assertThat(source.resolve(".ai-engineering/.local/server")).doesNotExist(); + } + @Test void captureRequiresExplicitDestinationAndSupportsInlineTextWithoutStartingServer() throws Exception { + Path source = Files.createDirectory(temporary.resolve("source")).toRealPath(); + Path destination = Files.createDirectory(temporary.resolve("destination")).toRealPath(); + new ProjectService().initializeLegacy(source, "Source"); new ProjectService().initializeLegacy(destination, "Destination"); + assertThat(cli(source, "request", "create", "Title", "--author", "agent", "--text", "body").code()).isEqualTo(2); + var captured = cli(temporary, "--project", destination.toString(), "request", "create", "Title", "--source-project", source.toString(), + "--source-work", "WRK-000A", "--author", "agent", "--text", "inline\ntext", "--format", "json"); + assertThat(captured.code()).as(captured.err()).isZero(); + assertThat(Documents.parseJson(captured.out(), RequestService.Created.class).request().sourceWork()).isEqualTo("WRK-000A"); + assertThat(cli(source, "request", "create", "Title", "--project", destination.toString(), "--author", "agent", "--text", "body", "--text-file", "missing").code()).isEqualTo(2); + assertThat(new RequestService().list(destination)).hasSize(1); + assertThat(destination.resolve(".ai-engineering/.local/server")).doesNotExist(); + var parser = new EngineeringCli(source).commandLine(new PrintWriter(new StringWriter()), new PrintWriter(new StringWriter())); + assertThat(InvocationPolicy.local(parser.parseArgs("request", "create", "Title", "--project", destination.toString(), "--author", "agent", "--text", "request list"))).isTrue(); + assertThat(InvocationPolicy.local(parser.parseArgs("request", "list"))).isFalse(); + assertThat(InvocationPolicy.readOnly(parser.parseArgs("request", "show", "REQ-" + UUID.randomUUID()))).isTrue(); + assertThat(InvocationPolicy.readOnly(parser.parseArgs("request", "incorporate", "REQ-" + UUID.randomUUID(), "--work", "WRK-0001", "--by", "handler"))).isFalse(); + } +} diff --git a/src/test/java/net/intrepid/aiengineering/request/RequestServiceTest.java b/src/test/java/net/intrepid/aiengineering/request/RequestServiceTest.java new file mode 100644 index 0000000..4157248 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/request/RequestServiceTest.java @@ -0,0 +1,172 @@ +package net.intrepid.aiengineering.request; + +import net.intrepid.aiengineering.discussion.DiscussionService; +import net.intrepid.aiengineering.filesystem.*; +import net.intrepid.aiengineering.project.ProjectService; +import net.intrepid.aiengineering.verification.VerificationService; +import net.intrepid.aiengineering.work.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.assertj.core.api.Assertions.*; + +class RequestServiceTest { + @TempDir Path temporary; + private Path source, destination; + private final RequestService requests = new RequestService(); + private final WorkService works = new WorkService(); + private void init(boolean sqlite) throws Exception { + source = Files.createDirectory(temporary.resolve("source")).toRealPath(); + destination = Files.createDirectory(temporary.resolve("destination")).toRealPath(); + new ProjectService().initializeLegacy(source, "Source"); + if (sqlite) new ProjectService().initializeSqlite(destination, "Destination"); + else new ProjectService().initializeLegacy(destination, "Destination"); + } + private Work work() { + return works.create(destination, "Handle Requests", "", "", "", List.of(), List.of(), List.of(), "tester"); + } + private RequestService.Created create(String text) { + return requests.create(destination, source, "Café request", text, "source-agent", "WRK-000F"); + } + @Test void capturesOnlyFilesEvenWhenSqlMemoryIsUnavailable() throws Exception { + init(true); + Files.move(destination.resolve(".ai-engineering/aie.db"), temporary.resolve("unavailable.db")); + String text = "\n## Café — 请求\r\n indentation\n---\n\nlast line without newline"; + var captured = create(text); + assertThat(requests.show(destination, captured.request().id())).isEqualTo(captured.request()); + assertThat(captured.request().text()).isEqualTo(text); + assertThat(captured.request().sourceProject()).isEqualTo(source.toString()); + assertThat(captured.request().sourceWork()).isEqualTo("WRK-000F"); + assertThat(Files.readString(Path.of(captured.path()))).startsWith("---\n").contains("documentVersion: 2", text); + assertThat(destination.resolve(".ai-engineering/aie.db")).doesNotExist(); + assertThat(destination.resolve(".ai-engineering/.local/server")).doesNotExist(); + assertThat(source.resolve(".ai-engineering/.local/server")).doesNotExist(); + } + @Test void concurrentProducersPublishCompleteIndependentFiles() throws Exception { + init(false); + try (var pool = Executors.newFixedThreadPool(8)) { + var calls = new ArrayList>(); + for (int i = 0; i < 32; i++) { + final int n = i; calls.add(pool.submit(() -> create("Message " + n + "\n" + "é".repeat(1000)))); + } + var ids = new HashSet(); + for (var call : calls) { + var result = call.get(10, TimeUnit.SECONDS); ids.add(result.request().id()); + assertThat(requests.show(destination, result.request().id())).isEqualTo(result.request()); + } + assertThat(ids).hasSize(32); + } + assertThat(requests.list(destination)).hasSize(32); + try (var files = Files.list(destination.resolve(".ai-engineering/requests"))) { + assertThat(files.toList()).hasSize(32).allMatch(p -> !p.getFileName().toString().startsWith(".")); + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) + void incorporationPreservesContextAndRetriesWithoutTheInputFile(boolean sqlite) throws Exception { + init(sqlite); var work = work(); var captured = create("Text\n\nOriginal é 请求\n"); + var result = requests.incorporate(destination, captured.request().id(), work.id(), "handler"); + assertThat(result.reused()).isFalse(); + assertThat(Path.of(captured.path())).doesNotExist(); + var history = new VerificationService().context(destination, work.id()).discussionHistory(); + assertThat(history).hasSize(1); + assertThat(history.getFirst().text()).contains(captured.request().id(), source.toString(), "source-agent", "WRK-000F") + .endsWith(captured.request().text()); + assertThat(history.getFirst().author()).isEqualTo("handler"); + assertThat(requests.incorporate(destination, captured.request().id(), work.id(), "handler").reused()).isTrue(); + assertThat(new DiscussionService().list(destination, work.id())).hasSize(1); + assertThat(requests.list(destination)).isEmpty(); + assertThat(new VerificationService().work(destination, work.id()).valid()).isTrue(); + } + @Test void failedPersistenceKeepsRequest() throws Exception { + init(true); var captured = create("Retain this"); + assertThatThrownBy(() -> requests.incorporate(destination, captured.request().id(), "WRK-FFFF", "handler")) + .isInstanceOf(ProtocolException.class).hasMessageContaining("not found"); + assertThat(Path.of(captured.path())).exists(); + assertThat(requests.list(destination)).containsExactly(captured.request()); + } + @Test void enclosingTransactionRollbackNeverRemovesInputOrPublishesContext() throws Exception { + init(true); var work = work(); var captured = create("Keep on rollback"); + assertThatThrownBy(() -> Filespace.locked(destination, () -> { + requests.incorporate(destination, captured.request().id(), work.id(), "handler"); + assertThat(Path.of(captured.path())).exists(); + throw ProtocolException.invalid("rollback injected"); + })).hasMessageContaining("rollback injected"); + assertThat(Path.of(captured.path())).exists(); + assertThat(new DiscussionService().list(destination, work.id())).isEmpty(); + requests.incorporate(destination, captured.request().id(), work.id(), "handler"); + assertThat(Path.of(captured.path())).doesNotExist(); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) + void interruptedCleanupIsDiscoverableAndRecoverableAfterPersistence(boolean sqlite) throws Exception { + init(sqlite); var work = work(); var captured = create("Survives cleanup failure"); + var failing = new RequestService(path -> { throw ProtocolException.invalid("cleanup interrupted"); }); + assertThatThrownBy(() -> failing.incorporate(destination, captured.request().id(), work.id(), "handler")) + .hasMessageContaining("cleanup interrupted"); + assertThat(new DiscussionService().list(destination, work.id())).hasSize(1); + assertThat(requests.list(destination)).containsExactly(captured.request()); + assertThat(requests.incorporate(destination, captured.request().id(), work.id(), "handler").reused()).isTrue(); + assertThat(new DiscussionService().list(destination, work.id())).hasSize(1); + assertThat(requests.list(destination)).isEmpty(); + } + @Test void concurrentConsumersIncorporateOnlyOnce() throws Exception { + init(true); var work = work(); var captured = create("One context entry"); + try (var pool = Executors.newFixedThreadPool(4)) { + var calls = new ArrayList>(); + for (int i = 0; i < 8; i++) calls.add(pool.submit(() -> requests.incorporate(destination, captured.request().id(), work.id(), "handler"))); + var results = new ArrayList(); + for (var call : calls) results.add(call.get(10, TimeUnit.SECONDS)); + assertThat(results.stream().filter(r -> !r.reused()).count()).isEqualTo(1); + assertThat(results.stream().map(RequestService.Incorporated::discussionId).distinct()).hasSize(1); + } + assertThat(new DiscussionService().list(destination, work.id())).hasSize(1); + } + @Test void changedContentAfterPersistenceIsRetainedAndConflictingRetriesAreRejected() throws Exception { + init(true); var work = work(); var captured = create("Original text"); + var editing = new RequestService(path -> Filespace.write(path, Filespace.read(path).replace("Original text", "Changed text"), true)); + assertThatThrownBy(() -> editing.incorporate(destination, captured.request().id(), work.id(), "handler")) + .hasMessageContaining("file retained"); + assertThat(Files.readString(Path.of(captured.path()))).contains("Changed text"); + assertThat(new DiscussionService().list(destination, work.id()).getFirst().text()).endsWith("Original text"); + assertThatThrownBy(() -> requests.incorporate(destination, captured.request().id(), work.id(), "handler")) + .hasMessageContaining("conflicts"); + assertThat(Path.of(captured.path())).exists(); + } + @Test void sameRequestCannotBeIncorporatedIntoAnotherWorkAndIdenticalRestoredInputIsCleanedUp() throws Exception { + init(true); var work = work(); var other = work(); var captured = create("One owner"); + String raw = Files.readString(Path.of(captured.path())); + requests.incorporate(destination, captured.request().id(), work.id(), "handler"); + Files.writeString(Path.of(captured.path()), raw); + assertThatThrownBy(() -> requests.incorporate(destination, captured.request().id(), other.id(), "handler")) + .hasMessageContaining("already belongs"); + assertThat(Path.of(captured.path())).exists(); + assertThat(new DiscussionService().list(destination, other.id())).isEmpty(); + assertThat(requests.incorporate(destination, captured.request().id(), work.id(), "handler").reused()).isTrue(); + assertThat(Path.of(captured.path())).doesNotExist(); + } + @Test void malformedUnsupportedAndSymlinkedRequestsRemainUntouched() throws Exception { + init(false); var work = work(); var captured = create("Original"); Path file = Path.of(captured.path()); + String raw = Files.readString(file); + for (String invalid : List.of(raw.replace("schemaVersion: 1", "schemaVersion: 99"), raw.replace(captured.request().id(), "REQ-invalid"), "---\nbroken")) { + Files.writeString(file, invalid); + assertThatThrownBy(() -> requests.incorporate(destination, captured.request().id(), work.id(), "handler")).isInstanceOf(ProtocolException.class); + assertThat(Files.readString(file)).isEqualTo(invalid); + } + Path external = temporary.resolve("external.md"); Files.writeString(external, raw); Files.delete(file); Files.createSymbolicLink(file, external); + assertThatThrownBy(() -> requests.show(destination, captured.request().id())).hasMessageContaining("Symlink"); + assertThat(Files.readString(external)).isEqualTo(raw); + assertThat(new DiscussionService().list(destination, work.id())).isEmpty(); + assertThatThrownBy(() -> requests.show(destination, "../escape")).hasMessageContaining("Invalid Request ID"); + } + @Test void missingDestinationDoesNotInitializeAProjectAndEmptyOrOversizedTextIsRejected() throws Exception { + init(false); Path missing = Files.createDirectory(temporary.resolve("not-a-project")); + assertThatThrownBy(() -> requests.create(missing, source, "Title", "Text", "agent", null)).hasMessageContaining("configuration"); + assertThat(missing.resolve(".ai-engineering")).doesNotExist(); + assertThatThrownBy(() -> create(" ")).hasMessageContaining("must not be blank"); + assertThatThrownBy(() -> create("é".repeat(600000))).hasMessageContaining("1 MiB"); + assertThat(requests.list(destination)).isEmpty(); + } +}