From 9a555cb3c6c124b8917acaaf6b704ab5d2782dc2 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Sun, 22 Nov 2026 23:08:47 +0000 Subject: [PATCH] feat: add per-project native server and SSE command streaming Keep Spring in a persistent project server with lightweight clients, managed start/stop, bounded SSE subscriptions, cursor recovery and durable mutation outcomes. Preserve SQLite authority and transaction limits, and document reproducible native measurements. Validation: 269 tests, 11 pipeline scenarios, full native/SSE smoke, native package verification and 17 installer tests passed. Implements WRK-000E / DEC-0001 / DEC-0002. --- README.md | 32 +- build.gradle.kts | 23 +- docs/architecture.md | 36 +- docs/benchmarks/local-server-initial.json | 438 +++++++++++++ docs/benchmarks/local-server-native.json | 440 +++++++++++++ .../local-server-sse-events-failed.json | 130 ++++ docs/benchmarks/local-server-sse-events.json | 244 +++++++ docs/benchmarks/local-server-sse-native.json | 599 ++++++++++++++++++ docs/latency-scenario.md | 11 +- docs/local-server-results.md | 78 +++ docs/local-server-sse-results.md | 103 +++ docs/local-server-sse.md | 54 ++ docs/local-server.md | 118 ++++ scripts/native-package-manifest.py | 4 +- scripts/native-smoke.sh | 13 +- scripts/native-sqlite-smoke.sh | 7 +- scripts/native-sse-smoke.py | 266 ++++++++ scripts/server-benchmark.py | 168 +++++ scripts/stop-fixture-servers.sh | 9 + scripts/test-install-native.py | 6 + scripts/verify-native-package.py | 26 + .../AiEngineeringApplication.java | 11 + .../intrepid/aiengineering/AieLauncher.java | 29 + .../intrepid/aiengineering/NativeHints.java | 7 +- .../aiengineering/cli/EngineeringCli.java | 76 ++- .../aiengineering/filesystem/Filespace.java | 12 +- .../filesystem/SqliteDatabase.java | 13 + .../localserver/InvocationClient.java | 93 +++ .../localserver/InvocationPolicy.java | 32 + .../aiengineering/localserver/JobEvents.java | 69 ++ .../localserver/LocalClient.java | 92 +++ .../localserver/ProjectServer.java | 150 +++++ .../localserver/RemoteOutput.java | 27 + .../localserver/RequestJobs.java | 251 ++++++++ .../localserver/ServerConnection.java | 75 +++ .../localserver/ServerIdentity.java | 21 + .../aiengineering/localserver/ServerJson.java | 20 + .../localserver/ServerLaunch.java | 30 + .../localserver/ServerManager.java | 107 ++++ .../localserver/ServerProtocol.java | 49 ++ .../localserver/ServerState.java | 100 +++ .../aiengineering/localserver/SseFrames.java | 17 + .../aiengineering/localserver/SseReader.java | 58 ++ .../aiengineering/localserver/SseStreams.java | 99 +++ .../localserver/package-info.java | 2 + src/main/resources/protocol/README.md | 20 +- .../aiengineering/DiscussionImportTest.java | 1 + .../aiengineering/InvocationPolicyTest.java | 46 ++ .../intrepid/aiengineering/JobEventsTest.java | 46 ++ .../aiengineering/LocalServerCleanup.java | 27 + .../aiengineering/LocalServerProcessTest.java | 147 +++++ .../PlanDecisionPromotionTest.java | 1 + .../aiengineering/ProcessContinuityTest.java | 14 +- .../aiengineering/ProjectServerTest.java | 45 ++ .../aiengineering/RequestJobsTest.java | 107 ++++ .../aiengineering/ServerStateTest.java | 39 ++ .../aiengineering/SqliteDatabaseTest.java | 24 + .../SqliteInvestigationTest.java | 1 + .../intrepid/aiengineering/SseClientTest.java | 80 +++ .../intrepid/aiengineering/SseHttpTest.java | 134 ++++ .../aiengineering/SseInputRecoveryTest.java | 73 +++ .../intrepid/aiengineering/SseReaderTest.java | 39 ++ .../aiengineering/WorkGuidanceTest.java | 1 + .../aiengineering/agent/CliTransportTest.java | 1 + 64 files changed, 5062 insertions(+), 29 deletions(-) create mode 100644 docs/benchmarks/local-server-initial.json create mode 100644 docs/benchmarks/local-server-native.json create mode 100644 docs/benchmarks/local-server-sse-events-failed.json create mode 100644 docs/benchmarks/local-server-sse-events.json create mode 100644 docs/benchmarks/local-server-sse-native.json create mode 100644 docs/local-server-results.md create mode 100644 docs/local-server-sse-results.md create mode 100644 docs/local-server-sse.md create mode 100644 docs/local-server.md create mode 100644 scripts/native-sse-smoke.py create mode 100644 scripts/server-benchmark.py create mode 100644 scripts/stop-fixture-servers.sh create mode 100644 src/main/java/net/intrepid/aiengineering/AieLauncher.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/InvocationClient.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/JobEvents.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/LocalClient.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ProjectServer.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/RemoteOutput.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/RequestJobs.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerConnection.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerIdentity.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerJson.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerLaunch.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerManager.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerProtocol.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/ServerState.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/SseFrames.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/SseReader.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/SseStreams.java create mode 100644 src/main/java/net/intrepid/aiengineering/localserver/package-info.java create mode 100644 src/test/java/net/intrepid/aiengineering/InvocationPolicyTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/JobEventsTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/LocalServerCleanup.java create mode 100644 src/test/java/net/intrepid/aiengineering/LocalServerProcessTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/ProjectServerTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/RequestJobsTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/ServerStateTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/SseClientTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/SseHttpTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/SseInputRecoveryTest.java create mode 100644 src/test/java/net/intrepid/aiengineering/SseReaderTest.java diff --git a/README.md b/README.md index fe13c22..2d51057 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ across people, AI agents, and sessions. It stores goals, discussions, decisions, plans, and quality results in a local SQLite database for each project. Use it in a single folder or across several source repositories. Git is optional. -SQLite runs inside AIE; no database server, model API or background service is required. +SQLite runs inside AIE. A lightweight client automatically starts and reuses a local +Spring server for each project, with native GraalVM as the default distribution. +No model API or separately managed database service is required. State stays outside Git by default. Versioning it is the developer's choice. ## What you can do @@ -128,6 +130,30 @@ The exported context brings together the Work's scope, discussion, decisions, plans, evidence references, and pending questions. `next-actions` suggests what to 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: + +```sh +aie start # Start or reuse; wait until ready +aie server status # Inspect process identity and active requests +aie start --idle-timeout-seconds 1800 # Configure idle shutdown for this instance +aie stop # Drain operations and stop; repeat safely +``` + +Each canonical project directory has its own automatically selected loopback port. +The default idle timeout is 30 minutes without active operations. A later command +can start a stopped server again. `aie status` keeps its engineering-status meaning. +Help, version and initialization run locally. The JVM JAR uses the same lifecycle +for development and diagnostics; the native package supplies the default runtime. + +Pending commands receive output and state through SSE and report their request ID +on stderr. Immediate results return directly. `aie server request ID` inspects a +recoverable result; `aie server cancel ID` requests cooperative cancellation. +After a crash, an unknown mutation outcome requires inspecting effects before retrying. +See [server operation and recovery](docs/local-server.md) and the +[measured SSE results](docs/local-server-sse-results.md). + ### Choose the next Work `work list`, `status`, and `next-actions` accept `--format table|csv|markdown|json`. @@ -293,6 +319,10 @@ Tests generate JUnit results and JaCoCo coverage. Open | [EPIC coordination](docs/epics.md) | Relationships and completion policies across Works | | [Local CLI adapters](docs/cli-adapters.md) | Provider setup and invocation contract | | [Architecture](docs/architecture.md) | Module boundaries and implementation design | +| [Local server](docs/local-server.md) | Startup, shutdown, isolation, limits and recovery | +| [Native measurements](docs/local-server-results.md) | Reproducible startup, roundtrip and memory results | +| [SSE protocol](docs/local-server-sse.md) | Event delivery, cursors, reconnection and resource bounds | +| [SSE measurements](docs/local-server-sse-results.md) | Current native results and concurrent streaming workload | | [Roadmap](docs/roadmap.md) | Implemented capabilities and planned work | | [Verification notes](docs/experiments.md) | Recorded experiments and validation results | diff --git a/build.gradle.kts b/build.gradle.kts index a7de470..e46f69d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,5 @@ import org.gradle.api.tasks.bundling.Compression +import java.security.MessageDigest plugins { java @@ -10,6 +11,24 @@ plugins { group = "net.intrepid" version = "0.1.0" +val serverIdentityDirectory = layout.buildDirectory.dir("generated/serverIdentity") +val serverBuildIdentity = tasks.register("serverBuildIdentity") { + val sources = fileTree("src/main") { include("**/*") } + inputs.files(sources, file("build.gradle.kts")) + outputs.file(serverIdentityDirectory.map { it.file("aie-build.txt") }) + doLast { + val digest = MessageDigest.getInstance("SHA-256") + (sources.files + file("build.gradle.kts")).sortedBy { it.path }.forEach { + digest.update(it.relativeTo(projectDir).path.toByteArray()) + digest.update(it.readBytes()) + } + val target = serverIdentityDirectory.get().file("aie-build.txt").asFile + target.parentFile.mkdirs() + target.writeText(digest.digest().joinToString("") { "%02x".format(it) } + "\n") + } +} +tasks.processResources { dependsOn(serverBuildIdentity); from(serverIdentityDirectory) } + tasks.withType().configureEach { from("LICENSE") { into("META-INF") } } @@ -67,6 +86,7 @@ val jenkinsPipelineTest = tasks.register("jenkinsPipelineTest") { } tasks.check { dependsOn(jenkinsPipelineTest) } springBoot { mainClass = "net.intrepid.aiengineering.AiEngineeringApplication" } +tasks.bootJar { mainClass.set("net.intrepid.aiengineering.AieLauncher") } val sqliteProbe = sourceSets.create("sqliteProbe") sqliteProbe.compileClasspath += sourceSets.main.get().output sqliteProbe.runtimeClasspath += sourceSets.main.get().output @@ -84,12 +104,13 @@ tasks.register("sqliteProbe") { } graalvmNative { binaries.named("main") { + mainClass.set("net.intrepid.aiengineering.AieLauncher") imageName = "ai-engineering" javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(25)) vendor.set(JvmVendorSpec.matching("GraalVM")) }) - buildArgs.addAll("--no-fallback", "-O1", "--enable-native-access=ALL-UNNAMED", + buildArgs.addAll("--no-fallback", "-O1", "--enable-native-access=ALL-UNNAMED", "--enable-url-protocols=http", "-Dorg.sqlite.lib.exportPath=${layout.buildDirectory.dir("native/nativeCompile").get().asFile}") } binaries.create("sqliteProbe") { diff --git a/docs/architecture.md b/docs/architecture.md index 2245014..0c69b45 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,7 +3,8 @@ AIE is a local engineering memory with two cycles: investigation/refinement and implementation, connected by DEC and Plan. OODA is adaptive; gates constrain delivery. The CLI records external observations and applies deterministic checks. It does not -execute repository commands, operate a server or provide distributed collaboration. +execute repository commands or provide distributed collaboration. A lightweight +client communicates with an automatically managed local server for each project. ## Runtime and modules @@ -13,6 +14,20 @@ GraalVM CE 25.5.5.0+3 is pinned in .sdkmanrc. Spring supplies process lifecycle services are ordinary Java classes with explicit project paths and no retained Work cache. Infrastructure stays outside immutable domain records. +AieLauncher handles client dispatch without opening Spring. The server starts a +persistent Spring context and a bounded JDK HTTP listener. AiEngineeringApplication +remains the Spring AOT application entry; the distribution uses AieLauncher and +explicitly selects that AOT application when starting its server. Picocli parses +prefixes and constructs the selected branch with fresh invocation objects; complete +catalogs remain available for help and diagnostics. + +Pending invocations subscribe to authenticated SSE; terminal immediate responses +remain JSON. JobEvents retains a bounded replay window and publishes under the job +monitor. SseStreams owns separate bounded writers and interrupts stalled socket +writes. InvocationClient resumes with a cursor and verifies output offsets/prefixes; +it never resubmits execution after a transport failure. Input and cancellation remain +POST operations. See [event protocol](local-server-sse.md). + | Module | Owns | May depend on | |---|---|---| | filesystem | Codecs, paths, SQLite sessions/typed storage, atomic external files and locks | none | @@ -26,6 +41,7 @@ cache. Infrastructure stays outside immutable domain records. | legacyimport | Explicit DF preview/import, preserved originals and provenance | filesystem, project, work, discussion, artifact | | 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 | ArchitectureTest enforces these boundaries. Work does not import Decision, Artifact or Verification. Verification coordinates across independently owned domains. @@ -43,6 +59,11 @@ bounded busy waits. Nested services share a transaction; failed nested mutations cannot be accidentally committed after an exception is caught. File-publication callbacks run after commit or rollback, after the connection closes. +The validated bootstrap choice is reused within that SQLite session, avoiding +repeated configuration/manifest decoding under the publication fence. It expires +with the transaction, never selects SQLite from file/connection existence, and +does not cache domain records or approvals. There is no JDBC connection pool. + SqliteRecords maps trusted record components to typed scalar columns and ordered child rows. Composite operational values have a domain codec, not serialized file content. List presence preserves null versus empty, necessary for historical hashes. @@ -100,11 +121,16 @@ not removed. Details: [migration](storage-migration.md). `nativePackage` builds AIE and the pinned SQLite diagnostic CLI with companion native libraries and a checksum manifest. Native hints cover operational records/resources. -The candidate verifier creates a disposable database with native AIE and reads it -with packaged sqlite3. Install preparation is distinct from activation: versioned +The candidate verifier creates a disposable database with native AIE, reads it +with packaged sqlite3, and verifies native server startup, build identity, command +roundtrips, SSE/input/recovery/cancellation and shutdown. Install preparation is distinct from activation: versioned releases, a current symlink and shortcuts are switched only after verification. -Installer tests use fake tools and disposable destinations. This Work did not run -an actual installer or modify the active distribution or consumer projects. +Installer tests use fake tools and disposable destinations. Build and verification +do not activate the candidate distribution or modify consumer projects. + +Local-server operational receipts live outside canonical memory; the database schema, +historical formats and authority rules are unchanged. See [the protocol and operating +limits](local-server.md) and [measured SSE results](local-server-sse-results.md). Primary references: [SQLite JDBC native support](https://github.com/xerial/sqlite-jdbc#graalvm-native-image-support), [SQLite transactions](https://sqlite.org/lang_transaction.html), diff --git a/docs/benchmarks/local-server-initial.json b/docs/benchmarks/local-server-initial.json new file mode 100644 index 0000000..f35a06e --- /dev/null +++ b/docs/benchmarks/local-server-initial.json @@ -0,0 +1,438 @@ +{ + "observedAt": "2026-11-22T20:09:27.588823+00:00", + "environment": { + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "logicalCpus": 10, + "initialLoadAverage": [ + 2.63427734375, + 2.87744140625, + 2.5302734375 + ], + "cpu": "Apple M2 Pro", + "physicalMemoryBytes": "17179869184" + }, + "method": { + "works": 100, + "notesPerWork": 10, + "storage": "sqlite", + "git": false, + "provider": false, + "freshClientPerSample": true, + "percentile": "nearest rank", + "cold": "process cold; OS file caches not flushed", + "command": [ + "work", + "show", + "WRK-0064", + "--format", + "json" + ] + }, + "candidate": { + "path": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "sha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "package": { + "schemaVersion": 1, + "aieVersion": "0.1.0", + "protocolVersion": 4, + "sqliteVersion": "3.54.1", + "localServerProtocol": 1, + "buildIdentity": "b1c5c0afb1ec3e1cfa26bb00069eefaaafa95feb898d3f6d42fdbab5a69ee3fe", + "files": { + "LICENSE": "975eef35ea2ca6532c53302a8bf202b99231cc7387ebbb022b1af1d58e4852b6", + "README.md": "584c14e6eb74928674c75d1778a692157f63723aad1f51b949dca1055e04f136", + "ai-engineering": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "docs/architecture.md": "64f6429677d8073f31d56882f42bed1fcab9820b1c6174026cf46149b90ffb5f", + "docs/cli-adapters.md": "bbf42d7953cb3ff48e75f0ce2228d83afc87c5e10b69d02d555bcd25ca3e32e1", + "docs/compatibility.md": "c127cb6440f561a976b696af5b99a9659da124a7151c170de3413e40cd377cfc", + "docs/discussion-import.md": "de1e09cd8b576da796a6af7dd4b4c8bac6ec08d8cf3c21389155b0710cf5ecda", + "docs/discussion-slice.md": "3aa8b75ddb6c7ba546740594d6709ba78fcffc553a63e0366cd6b56771eae1e5", + "docs/epics.md": "67ea357a91f1fbe64330b1b5a4fd26432e846bd687f961e23e3deca6cb23ceba", + "docs/experiments.md": "cf6ed18390d16f9483bb8a26f77b3ae040e1cabdc6570ab3300bb1bfb4cd2646", + "docs/latency-scenario.md": "d98b5a16c00b6e97f2af33d736515252c39bfdb2ea0ca214c22efbba69ef1183", + "docs/legacy-file-storage.md": "97613b0b58baf02f9c5ef31dfe95ee4b33ef742296c6d94ca3e660205b92d598", + "docs/local-server.md": "26ab737dfa424a35eceffe25177a7b6b006e535e7ccf2c2df41eb97e69ad498e", + "docs/plan-consolidation.md": "9fdc22aab9975e46bb67b1b1aefab0e71af3f069762770662e590483ae1a68cc", + "docs/protocol.md": "c5bf6bf2d459312a3d92e477a1b43dcbdd86aa41c45bd5c10a314560df8a419a", + "docs/roadmap.md": "b3f7d396ad9c4a41a8a02136529f628febf53c4bf2b97acb331668efb76dbeff", + "docs/sqlite-migration-design.md": "21f775427602af06820e6fbeb4d08ff639c803bf923aa0277574df8b2a60488d", + "docs/storage-migration.md": "ac54b7bd2c963367a47d488a32c16720154243378e82b10ba3b78209c8d16aad", + "docs/work-guidance.md": "45e7934db455d427ac1374a1694707d8075ca80b63eef7e13b875e1531474562", + "libawt.dylib": "c794235bd609c8ce066aa3d5b2a3dd5b99d40b5fcd595aceddf4f54051be5d24", + "libawt_lwawt.dylib": "ff09e5e47be4b96c3560b42c890c851ff18e99ddf4d8085525a3244c0aeeba4e", + "libfontmanager.dylib": "3b33fb98dc2937c495ca7833396ad1d613e261e5b6164115821915353ddcdde4", + "libfreetype.dylib": "9a88ef02fe6522f024c2d1e2dee8c1dd053a8ab87d1f61d2b62ea1806b2b189d", + "libjava.dylib": "465aac4cf94ccbd19c4849b89c61284b459c648ecc0f813e8452ad8c6905f444", + "libjavajpeg.dylib": "9370b79daf271c2da78275baa782cfb987c49f0a554585fd35a9edf32211e716", + "libjvm.dylib": "d535b761c960e4f4d1867fc2a977dbc28f7d8fb2a32d7db9bf478c56c175b71d", + "liblcms.dylib": "8d554b5fdb043bb7daff0c305c4464e934387576cb64955b39889ff29a7b0c60", + "libmlib_image.dylib": "e7d5a248aa7956f476aaba2483d7e7684406c3eff3c3984a2a5bba4f9e05fb30", + "libosxapp.dylib": "18fbd74e41bad5e3cb4e6c1a212c75a9590aa863947d5edcdd3571aa5e550105", + "libsqlitejdbc.dylib": "47fa68b43f34552fbfedeed25e82875a42cfd53e81c33c7cee20ac3f729c060e", + "sqlite3": "440575f732a7ff117b604ddd87d742833685a3a6cb3faff414c258b87fc2204c" + } + } + }, + "baseline": { + "path": "/private/tmp/aie-wrk000e-baseline-package/ai-engineering", + "sha256": "ba200c28e3ddc6d78668aecf5587524d718902fc6c5eeb607bbca07ee8947658", + "version": "ai-engineering 0.1.0", + "roundtrip": { + "samples": 100, + "minMs": 243.414709, + "p50Ms": 249.232, + "p95Ms": 256.384958, + "maxMs": 276.045416, + "rawMs": [ + 253.460958, + 247.53425, + 250.855291, + 252.944958, + 250.76, + 250.65525, + 249.367625, + 252.943166, + 247.937416, + 247.2745, + 249.418375, + 276.045416, + 248.825959, + 257.40925, + 250.917583, + 250.205833, + 246.528083, + 243.860375, + 250.7645, + 250.044166, + 247.005875, + 248.437, + 250.989875, + 247.107917, + 248.397042, + 251.164166, + 250.855625, + 247.628542, + 250.839125, + 251.474416, + 251.775125, + 250.481792, + 251.594417, + 248.764583, + 245.628833, + 244.895375, + 243.526709, + 243.813916, + 253.859875, + 243.666459, + 243.414709, + 245.440208, + 255.717333, + 257.349834, + 254.672125, + 253.430625, + 255.106209, + 255.367083, + 253.738792, + 250.981917, + 254.152875, + 255.907625, + 256.452209, + 249.82225, + 251.442958, + 256.384958, + 254.785834, + 259.184292, + 250.725166, + 251.165458, + 246.640708, + 245.890666, + 250.517833, + 247.548083, + 249.804167, + 246.921209, + 247.379542, + 245.696875, + 245.823333, + 247.739792, + 247.041042, + 251.131208, + 245.954833, + 246.143125, + 249.546916, + 250.519167, + 246.057583, + 246.0765, + 247.93425, + 251.197083, + 248.855125, + 246.107417, + 248.090958, + 249.096375, + 248.9735, + 249.902791, + 249.659458, + 247.771667, + 245.787209, + 244.618709, + 248.1785, + 247.551958, + 247.265042, + 246.208875, + 248.308375, + 249.624125, + 245.449083, + 245.749958, + 247.325167, + 248.211708 + ] + } + }, + "fixture": { + "version": "ai-engineering 0.1.0", + "binary": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "binarySha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "storage": "sqlite", + "works": 100, + "entriesPerWork": 10, + "selectedWork": "WRK-0064", + "measurementPerformed": false + }, + "readiness": { + "samples": 10, + "minMs": 270.474584, + "p50Ms": 297.444521, + "p95Ms": 307.406166, + "maxMs": 307.406166, + "rawMs": [ + 270.474584, + 297.465, + 306.412375, + 307.406166, + 288.557541, + 294.88075, + 297.424042, + 303.892958, + 295.419, + 303.751958 + ] + }, + "firstUse": { + "samples": 10, + "minMs": 718.810958, + "p50Ms": 727.360708, + "p95Ms": 758.715417, + "maxMs": 758.715417, + "rawMs": [ + 758.715417, + 728.198291, + 730.21775, + 732.192958, + 726.523125, + 728.715167, + 722.615667, + 726.064416, + 718.810958, + 724.243583 + ] + }, + "warm": { + "samples": 100, + "minMs": 599.206041, + "p50Ms": 621.7846460000001, + "p95Ms": 652.347541, + "maxMs": 670.564208, + "rawMs": [ + 641.382792, + 635.421625, + 636.44975, + 628.610542, + 637.319917, + 640.229708, + 641.501583, + 623.680125, + 637.978208, + 640.96375, + 634.2935, + 626.224166, + 639.844334, + 640.969458, + 634.38325, + 634.171875, + 670.564208, + 656.990833, + 654.89275, + 662.157333, + 647.789667, + 651.245958, + 653.977833, + 626.660542, + 616.85925, + 623.365416, + 622.049667, + 652.347541, + 630.473208, + 627.341291, + 621.357, + 621.036166, + 617.587708, + 618.867, + 619.630583, + 621.714333, + 618.821208, + 616.668875, + 622.186792, + 620.419875, + 616.205875, + 618.786959, + 617.924625, + 605.393292, + 606.733791, + 621.340916, + 620.093458, + 618.730459, + 618.803166, + 621.718333, + 627.430167, + 634.81675, + 629.812958, + 618.897291, + 620.678167, + 615.395167, + 620.096709, + 621.898084, + 619.884666, + 616.880125, + 617.377292, + 624.740583, + 626.348417, + 619.614917, + 628.931583, + 631.439834, + 650.049458, + 647.832291, + 622.691417, + 619.821416, + 619.749208, + 603.352917, + 610.881958, + 623.378541, + 615.418667, + 622.208917, + 618.207583, + 616.284, + 622.625041, + 612.51825, + 619.217125, + 624.190208, + 631.766917, + 622.846459, + 619.75775, + 621.850959, + 617.246958, + 612.323834, + 620.303292, + 620.114458, + 618.352416, + 617.691167, + 617.720875, + 622.782625, + 622.794458, + 614.317333, + 617.770125, + 615.237041, + 599.206041, + 606.190541 + ] + }, + "memory": [ + { + "projects": 1, + "processes": [ + { + "pid": 29395, + "rssMiB": 40.953125 + } + ], + "totalRssMiB": 40.953125 + }, + { + "projects": 5, + "processes": [ + { + "pid": 29395, + "rssMiB": 40.984375 + }, + { + "pid": 29400, + "rssMiB": 87.984375 + }, + { + "pid": 29403, + "rssMiB": 87.828125 + }, + { + "pid": 29406, + "rssMiB": 87.953125 + }, + { + "pid": 29409, + "rssMiB": 87.796875 + } + ], + "totalRssMiB": 392.546875 + }, + { + "projects": 10, + "processes": [ + { + "pid": 29395, + "rssMiB": 41.03125 + }, + { + "pid": 29400, + "rssMiB": 87.96875 + }, + { + "pid": 29403, + "rssMiB": 87.8125 + }, + { + "pid": 29406, + "rssMiB": 87.9375 + }, + { + "pid": 29409, + "rssMiB": 87.78125 + }, + { + "pid": 29423, + "rssMiB": 88.515625 + }, + { + "pid": 29426, + "rssMiB": 87.9375 + }, + { + "pid": 29429, + "rssMiB": 87.96875 + }, + { + "pid": 29432, + "rssMiB": 88.0 + }, + { + "pid": 29435, + "rssMiB": 88.234375 + } + ], + "totalRssMiB": 833.1875 + } + ], + "acceptance": { + "warmP95AtMost100Ms": false, + "allReadinessAtMost1000Ms": true + } +} diff --git a/docs/benchmarks/local-server-native.json b/docs/benchmarks/local-server-native.json new file mode 100644 index 0000000..437cb65 --- /dev/null +++ b/docs/benchmarks/local-server-native.json @@ -0,0 +1,440 @@ +{ + "observedAt": "2026-11-22T21:05:40.551988+00:00", + "environment": { + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "logicalCpus": 10, + "initialLoadAverage": [ + 5.93603515625, + 4.7822265625, + 3.5390625 + ], + "cpu": "Apple M2 Pro", + "physicalMemoryBytes": "17179869184" + }, + "method": { + "works": 100, + "notesPerWork": 10, + "storage": "sqlite", + "git": false, + "provider": false, + "freshClientPerSample": true, + "percentile": "nearest rank", + "cold": "process cold; OS file caches not flushed", + "copiedFixture": "/private/tmp/aie-wrk000e-benchmark-1/nominal", + "command": [ + "work", + "show", + "WRK-0064", + "--format", + "json" + ], + "memoryWorkload": "Fresh server then work show per project; first project has 100 Works/1000 notes, remaining projects one Work each. Summed process RSS, shared pages may be counted repeatedly." + }, + "candidate": { + "path": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "sha256": "4764f522935d8fdb1600f5a925e845ddb62689a4743a9e17f8eb433347d1e8c2", + "package": { + "schemaVersion": 1, + "aieVersion": "0.1.0", + "protocolVersion": 4, + "sqliteVersion": "3.54.1", + "localServerProtocol": 1, + "buildIdentity": "79f2d2b1a929f76c59d3214ffe55a635e87ab9f536e3f8c28f88438f2a421747", + "files": { + "LICENSE": "975eef35ea2ca6532c53302a8bf202b99231cc7387ebbb022b1af1d58e4852b6", + "README.md": "584c14e6eb74928674c75d1778a692157f63723aad1f51b949dca1055e04f136", + "ai-engineering": "4764f522935d8fdb1600f5a925e845ddb62689a4743a9e17f8eb433347d1e8c2", + "docs/architecture.md": "64f6429677d8073f31d56882f42bed1fcab9820b1c6174026cf46149b90ffb5f", + "docs/cli-adapters.md": "bbf42d7953cb3ff48e75f0ce2228d83afc87c5e10b69d02d555bcd25ca3e32e1", + "docs/compatibility.md": "c127cb6440f561a976b696af5b99a9659da124a7151c170de3413e40cd377cfc", + "docs/discussion-import.md": "de1e09cd8b576da796a6af7dd4b4c8bac6ec08d8cf3c21389155b0710cf5ecda", + "docs/discussion-slice.md": "3aa8b75ddb6c7ba546740594d6709ba78fcffc553a63e0366cd6b56771eae1e5", + "docs/epics.md": "67ea357a91f1fbe64330b1b5a4fd26432e846bd687f961e23e3deca6cb23ceba", + "docs/experiments.md": "cf6ed18390d16f9483bb8a26f77b3ae040e1cabdc6570ab3300bb1bfb4cd2646", + "docs/latency-scenario.md": "d98b5a16c00b6e97f2af33d736515252c39bfdb2ea0ca214c22efbba69ef1183", + "docs/legacy-file-storage.md": "97613b0b58baf02f9c5ef31dfe95ee4b33ef742296c6d94ca3e660205b92d598", + "docs/local-server.md": "26ab737dfa424a35eceffe25177a7b6b006e535e7ccf2c2df41eb97e69ad498e", + "docs/plan-consolidation.md": "9fdc22aab9975e46bb67b1b1aefab0e71af3f069762770662e590483ae1a68cc", + "docs/protocol.md": "c5bf6bf2d459312a3d92e477a1b43dcbdd86aa41c45bd5c10a314560df8a419a", + "docs/roadmap.md": "b3f7d396ad9c4a41a8a02136529f628febf53c4bf2b97acb331668efb76dbeff", + "docs/sqlite-migration-design.md": "21f775427602af06820e6fbeb4d08ff639c803bf923aa0277574df8b2a60488d", + "docs/storage-migration.md": "ac54b7bd2c963367a47d488a32c16720154243378e82b10ba3b78209c8d16aad", + "docs/work-guidance.md": "45e7934db455d427ac1374a1694707d8075ca80b63eef7e13b875e1531474562", + "libawt.dylib": "c794235bd609c8ce066aa3d5b2a3dd5b99d40b5fcd595aceddf4f54051be5d24", + "libawt_lwawt.dylib": "ff09e5e47be4b96c3560b42c890c851ff18e99ddf4d8085525a3244c0aeeba4e", + "libfontmanager.dylib": "3b33fb98dc2937c495ca7833396ad1d613e261e5b6164115821915353ddcdde4", + "libfreetype.dylib": "9a88ef02fe6522f024c2d1e2dee8c1dd053a8ab87d1f61d2b62ea1806b2b189d", + "libjava.dylib": "465aac4cf94ccbd19c4849b89c61284b459c648ecc0f813e8452ad8c6905f444", + "libjavajpeg.dylib": "9370b79daf271c2da78275baa782cfb987c49f0a554585fd35a9edf32211e716", + "libjvm.dylib": "d535b761c960e4f4d1867fc2a977dbc28f7d8fb2a32d7db9bf478c56c175b71d", + "liblcms.dylib": "8d554b5fdb043bb7daff0c305c4464e934387576cb64955b39889ff29a7b0c60", + "libmlib_image.dylib": "e7d5a248aa7956f476aaba2483d7e7684406c3eff3c3984a2a5bba4f9e05fb30", + "libosxapp.dylib": "18fbd74e41bad5e3cb4e6c1a212c75a9590aa863947d5edcdd3571aa5e550105", + "libsqlitejdbc.dylib": "47fa68b43f34552fbfedeed25e82875a42cfd53e81c33c7cee20ac3f729c060e", + "sqlite3": "440575f732a7ff117b604ddd87d742833685a3a6cb3faff414c258b87fc2204c" + } + } + }, + "baseline": { + "path": "/private/tmp/aie-wrk000e-baseline-package/ai-engineering", + "sha256": "ba200c28e3ddc6d78668aecf5587524d718902fc6c5eeb607bbca07ee8947658", + "version": "ai-engineering 0.1.0", + "roundtrip": { + "samples": 100, + "minMs": 247.445416, + "p50Ms": 252.974063, + "p95Ms": 261.317167, + "maxMs": 304.625167, + "rawMs": [ + 268.521708, + 254.163208, + 256.5805, + 261.317167, + 261.239666, + 253.7125, + 257.63675, + 256.982542, + 267.667291, + 275.230333, + 304.625167, + 258.132, + 258.471917, + 259.315084, + 258.914041, + 259.164042, + 257.749292, + 262.5925, + 258.094667, + 257.1155, + 259.613375, + 253.663459, + 257.907166, + 255.933375, + 252.463625, + 253.408792, + 255.750458, + 253.95325, + 253.314583, + 257.598625, + 256.163916, + 251.938834, + 253.836416, + 251.739417, + 259.45825, + 256.917875, + 253.146458, + 251.406209, + 252.231542, + 253.109917, + 260.89875, + 257.021667, + 249.817, + 253.119375, + 255.144666, + 252.735417, + 255.235792, + 253.881875, + 247.609333, + 253.901875, + 258.764708, + 253.395709, + 251.726, + 251.737917, + 260.889166, + 256.221375, + 249.932084, + 250.57375, + 253.190459, + 249.324666, + 250.355708, + 250.061625, + 252.521708, + 251.533917, + 251.143, + 249.875917, + 251.143125, + 249.146625, + 249.2565, + 250.736, + 252.253917, + 252.331083, + 249.038334, + 251.9965, + 248.102125, + 253.843042, + 253.604666, + 250.204083, + 248.605334, + 250.113792, + 251.64275, + 249.621666, + 251.095542, + 249.856709, + 249.101167, + 248.752667, + 250.381458, + 249.596791, + 248.69575, + 248.897709, + 251.597042, + 249.719542, + 251.313083, + 247.445416, + 250.167083, + 250.555209, + 250.437209, + 254.228291, + 252.838209, + 249.669208 + ] + } + }, + "fixture": { + "version": "ai-engineering 0.1.0", + "binary": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "binarySha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "storage": "sqlite", + "works": 100, + "entriesPerWork": 10, + "selectedWork": "WRK-0064", + "measurementPerformed": false + }, + "readiness": { + "samples": 10, + "minMs": 282.047083, + "p50Ms": 285.55010400000003, + "p95Ms": 291.382583, + "maxMs": 291.382583, + "rawMs": [ + 283.0605, + 285.501125, + 285.599083, + 287.131917, + 284.372167, + 291.382583, + 287.331959, + 282.047083, + 285.464584, + 289.92775 + ] + }, + "firstUse": { + "samples": 10, + "minMs": 100.095708, + "p50Ms": 111.2676455, + "p95Ms": 113.496833, + "maxMs": 113.496833, + "rawMs": [ + 112.433709, + 113.496833, + 111.254208, + 111.281083, + 112.570084, + 108.870625, + 100.095708, + 106.646417, + 105.978834, + 111.470458 + ] + }, + "warm": { + "samples": 100, + "minMs": 26.557542, + "p50Ms": 35.218104, + "p95Ms": 41.14075, + "maxMs": 42.382333, + "rawMs": [ + 33.88125, + 36.989583, + 34.185625, + 29.017625, + 27.42275, + 28.245041, + 29.785333, + 29.249541, + 28.716958, + 30.025958, + 30.989417, + 29.065208, + 29.590458, + 36.089584, + 30.737875, + 26.557542, + 31.29225, + 32.926042, + 33.800708, + 34.699875, + 33.855541, + 34.618083, + 31.49375, + 35.277584, + 32.1785, + 33.593083, + 31.66925, + 33.369875, + 34.948667, + 35.501875, + 35.512917, + 35.540625, + 36.302042, + 32.873209, + 31.992708, + 33.572792, + 31.732875, + 30.520917, + 32.404167, + 33.450208, + 32.768791, + 34.907958, + 35.174709, + 33.51675, + 33.488041, + 31.866125, + 40.012125, + 36.609209, + 34.749792, + 35.063667, + 35.200666, + 33.954875, + 34.587375, + 35.932417, + 35.235542, + 42.052709, + 36.228166, + 40.43725, + 40.294458, + 35.560459, + 33.457584, + 37.474333, + 34.867917, + 36.002583, + 34.254167, + 34.740208, + 36.901667, + 35.502666, + 37.060042, + 38.721458, + 36.296792, + 41.23625, + 36.4405, + 35.404042, + 38.128375, + 37.312917, + 37.402708, + 38.815875, + 41.14075, + 37.794, + 40.049333, + 36.435208, + 38.26925, + 36.971208, + 39.96675, + 35.615459, + 36.847042, + 41.504542, + 37.211541, + 40.59225, + 38.550666, + 42.23325, + 36.535041, + 42.382333, + 37.893375, + 38.973959, + 34.611125, + 33.259667, + 36.928208, + 37.128541 + ] + }, + "memory": [ + { + "projects": 1, + "processes": [ + { + "pid": 31132, + "rssMiB": 48.515625 + } + ], + "totalRssMiB": 48.515625 + }, + { + "projects": 5, + "processes": [ + { + "pid": 31132, + "rssMiB": 48.546875 + }, + { + "pid": 31142, + "rssMiB": 48.578125 + }, + { + "pid": 31150, + "rssMiB": 48.546875 + }, + { + "pid": 31157, + "rssMiB": 48.53125 + }, + { + "pid": 31165, + "rssMiB": 48.484375 + } + ], + "totalRssMiB": 242.6875 + }, + { + "projects": 10, + "processes": [ + { + "pid": 31132, + "rssMiB": 48.59375 + }, + { + "pid": 31142, + "rssMiB": 48.609375 + }, + { + "pid": 31150, + "rssMiB": 48.578125 + }, + { + "pid": 31157, + "rssMiB": 48.5625 + }, + { + "pid": 31165, + "rssMiB": 48.515625 + }, + { + "pid": 31182, + "rssMiB": 48.484375 + }, + { + "pid": 31189, + "rssMiB": 48.515625 + }, + { + "pid": 31196, + "rssMiB": 48.46875 + }, + { + "pid": 31203, + "rssMiB": 48.5625 + }, + { + "pid": 31230, + "rssMiB": 48.578125 + } + ], + "totalRssMiB": 485.46875 + } + ], + "acceptance": { + "warmP95AtMost100Ms": true, + "allReadinessAtMost1000Ms": true + } +} diff --git a/docs/benchmarks/local-server-sse-events-failed.json b/docs/benchmarks/local-server-sse-events-failed.json new file mode 100644 index 0000000..3dd03ca --- /dev/null +++ b/docs/benchmarks/local-server-sse-events-failed.json @@ -0,0 +1,130 @@ +{ + "platform": "macOS-27.2.1-arm64-arm-64bit", + "binarySha256": "4c825e3a4477256160494f8d18bd428bdc1a6d0e734fdaf510bd7782826ee420", + "buildIdentity": "d0216aa7622b5f099c02986c32bef2acf909ad6888e08647a75ad9f85533d050", + "method": "Input POST start to first subsequent stdout/input/terminal SSE event, including command work and control response; no human think time.", + "concurrentStreams": 4, + "questionsPerStream": 10, + "fixture": { + "version": "ai-engineering 0.1.0", + "binary": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "binarySha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "storage": "sqlite", + "works": 100, + "entriesPerWork": 10, + "selectedWork": "WRK-0064", + "measurementPerformed": false + }, + "queriesWithStreams": { + "samples": 100, + "p50Ms": 36.908916500000004, + "p95Ms": 42.287042, + "maxMs": 54.370083, + "rawMs": [ + 29.061625, + 30.812708, + 35.137042, + 34.391625, + 35.152833, + 34.681458, + 32.974583, + 33.143334, + 37.213333, + 34.241666, + 37.68025, + 36.714542, + 37.758125, + 32.081542, + 34.110875, + 31.506125, + 36.67975, + 33.72975, + 37.643833, + 37.384542, + 33.227125, + 33.860416, + 34.583125, + 33.560166, + 34.626417, + 36.974208, + 54.370083, + 40.227459, + 36.065959, + 40.296625, + 42.965458, + 42.287042, + 39.87025, + 38.923, + 46.087208, + 37.147625, + 38.708667, + 38.212667, + 37.192959, + 35.6235, + 37.727416, + 37.290583, + 36.60575, + 38.346625, + 35.897041, + 36.751292, + 36.336167, + 38.390833, + 35.607792, + 38.6025, + 34.587375, + 33.771542, + 34.986458, + 32.811625, + 34.311, + 32.764541, + 35.361167, + 33.825958, + 37.112583, + 35.865667, + 36.8035, + 38.546875, + 38.119041, + 38.014334, + 37.472916, + 36.977459, + 37.405541, + 38.740042, + 40.783709, + 40.740708, + 43.048875, + 42.629, + 37.59925, + 36.089625, + 33.967708, + 35.899042, + 36.072958, + 35.907917, + 32.952916, + 31.429917, + 32.08325, + 32.594541, + 32.516583, + 36.769208, + 37.71525, + 36.843625, + 39.13525, + 37.269959, + 38.642625, + 39.363833, + 38.671875, + 40.129, + 39.107125, + 36.684209, + 38.883333, + 38.262291, + 38.091459, + 39.192541, + 40.813125, + 40.971 + ] + }, + "rssWithStreamsMiB": 63.0625, + "failure": "Native SSE job failed: COMPLETED exit=4 stderr=Project publication is busy; local writer wait exceeded 2000 ms\n" +} diff --git a/docs/benchmarks/local-server-sse-events.json b/docs/benchmarks/local-server-sse-events.json new file mode 100644 index 0000000..13e136f --- /dev/null +++ b/docs/benchmarks/local-server-sse-events.json @@ -0,0 +1,244 @@ +{ + "platform": "macOS-27.2.1-arm64-arm-64bit", + "binarySha256": "2fa0f168bfb8e1ba11edbcd5cdda2a6b150726f86d9c11e77ee26c21ce7fc887", + "buildIdentity": "c891da8913045080a02d7b977a259d097e30864a5487e230d0ec7d5d4e78daff", + "method": "Input POST start to first subsequent stdout/input/terminal SSE event, including command work and control response; no human think time.", + "concurrentStreams": 4, + "questionsPerStream": 10, + "fixture": { + "version": "ai-engineering 0.1.0", + "binary": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "binarySha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "storage": "sqlite", + "works": 100, + "entriesPerWork": 10, + "selectedWork": "WRK-0064", + "measurementPerformed": false + }, + "queriesWithStreams": { + "samples": 100, + "p50Ms": 44.939021, + "p95Ms": 55.1795, + "maxMs": 62.78025, + "rawMs": [ + 28.76975, + 29.987667, + 34.436833, + 33.418125, + 32.68275, + 32.851834, + 33.036, + 33.84675, + 36.752292, + 41.603583, + 42.806416, + 56.994542, + 42.976417, + 42.95225, + 45.03725, + 37.020375, + 35.761708, + 33.717209, + 34.224291, + 35.327, + 39.704708, + 34.02625, + 33.536916, + 36.447041, + 40.812459, + 44.840792, + 44.118708, + 51.321875, + 46.081875, + 43.322375, + 44.472917, + 48.500417, + 45.077125, + 42.26125, + 46.487334, + 46.109, + 45.715625, + 47.799042, + 45.607292, + 62.78025, + 49.805792, + 48.930291, + 50.6305, + 45.726041, + 48.121625, + 52.496792, + 55.1795, + 56.541833, + 51.401459, + 48.596625, + 47.12175, + 50.265292, + 46.533125, + 51.594209, + 49.8065, + 50.667583, + 50.429458, + 48.414625, + 44.264417, + 42.545958, + 39.16125, + 38.935208, + 40.905625, + 42.612917, + 45.348792, + 46.701167, + 42.857208, + 46.396667, + 50.000833, + 52.979667, + 51.240292, + 47.554334, + 45.697791, + 46.023958, + 42.536417, + 39.550959, + 36.817542, + 39.571083, + 42.350417, + 35.259083, + 37.168458, + 35.837, + 39.118208, + 38.462333, + 38.162916, + 41.72625, + 43.378834, + 47.599583, + 44.220416, + 44.505459, + 47.966667, + 49.48375, + 49.536625, + 48.56825, + 54.346083, + 51.56225, + 56.096375, + 49.904917, + 49.791625, + 55.821958 + ] + }, + "rssWithStreamsMiB": 63.703125, + "jobs": [ + { + "events": 104, + "inputToEventMs": [ + 128.174917, + 429.247417, + 444.289333, + 451.0225, + 464.951709, + 473.534208, + 486.40725, + 500.553125, + 520.214583, + 532.23025 + ], + "stdoutSha256": "931bd0cd851a4b422e2c7066a689601ab6a88a62c70d9015d3b4f614944b8786" + }, + { + "events": 104, + "inputToEventMs": [ + 235.451542, + 435.689666, + 442.981666, + 453.538916, + 465.441084, + 478.091375, + 489.298541, + 506.608042, + 525.012583, + 537.225666 + ], + "stdoutSha256": "931bd0cd851a4b422e2c7066a689601ab6a88a62c70d9015d3b4f614944b8786" + }, + { + "events": 104, + "inputToEventMs": [ + 344.050542, + 437.069834, + 444.476667, + 457.928542, + 468.600833, + 482.400584, + 491.982916, + 511.669375, + 525.532417, + 542.435416 + ], + "stdoutSha256": "931bd0cd851a4b422e2c7066a689601ab6a88a62c70d9015d3b4f614944b8786" + }, + { + "events": 104, + "inputToEventMs": [ + 451.012875, + 441.048666, + 447.26875, + 463.7365, + 468.111042, + 484.093, + 498.831, + 515.019542, + 529.620667, + 543.795083 + ], + "stdoutSha256": "931bd0cd851a4b422e2c7066a689601ab6a88a62c70d9015d3b4f614944b8786" + } + ], + "inputToEvent": { + "samples": 40, + "p50Ms": 471.0675205, + "p95Ms": 537.225666, + "maxMs": 543.795083, + "rawMs": [ + 128.174917, + 429.247417, + 444.289333, + 451.0225, + 464.951709, + 473.534208, + 486.40725, + 500.553125, + 520.214583, + 532.23025, + 235.451542, + 435.689666, + 442.981666, + 453.538916, + 465.441084, + 478.091375, + 489.298541, + 506.608042, + 525.012583, + 537.225666, + 344.050542, + 437.069834, + 444.476667, + 457.928542, + 468.600833, + 482.400584, + 491.982916, + 511.669375, + 525.532417, + 542.435416, + 451.012875, + 441.048666, + 447.26875, + 463.7365, + 468.111042, + 484.093, + 498.831, + 515.019542, + 529.620667, + 543.795083 + ] + }, + "cancellationVerified": true +} diff --git a/docs/benchmarks/local-server-sse-native.json b/docs/benchmarks/local-server-sse-native.json new file mode 100644 index 0000000..a6269df --- /dev/null +++ b/docs/benchmarks/local-server-sse-native.json @@ -0,0 +1,599 @@ +{ + "observedAt": "2026-11-22T22:34:13.785795+00:00", + "environment": { + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "logicalCpus": 10, + "initialLoadAverage": [ + 3.5703125, + 4.8671875, + 4.8251953125 + ], + "cpu": "Apple M2 Pro", + "physicalMemoryBytes": "17179869184" + }, + "method": { + "works": 100, + "notesPerWork": 10, + "storage": "sqlite", + "git": false, + "provider": false, + "freshClientPerSample": true, + "percentile": "nearest rank", + "cold": "process cold; OS file caches not flushed", + "copiedFixture": "/private/tmp/aie-wrk000e-benchmark-1/nominal", + "command": [ + "work", + "show", + "WRK-0064", + "--format", + "json" + ], + "memoryWorkload": "Fresh server then work show per project; first project has 100 Works/1000 notes, remaining projects one Work each. Summed process RSS, shared pages may be counted repeatedly." + }, + "candidate": { + "path": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "sha256": "2fa0f168bfb8e1ba11edbcd5cdda2a6b150726f86d9c11e77ee26c21ce7fc887", + "package": { + "schemaVersion": 1, + "aieVersion": "0.1.0", + "protocolVersion": 4, + "sqliteVersion": "3.54.1", + "localServerProtocol": 1, + "localServerEvents": "sse", + "buildIdentity": "c891da8913045080a02d7b977a259d097e30864a5487e230d0ec7d5d4e78daff", + "files": { + "LICENSE": "975eef35ea2ca6532c53302a8bf202b99231cc7387ebbb022b1af1d58e4852b6", + "README.md": "79b01d93a0c639d727894db6c5040790c5ee05aa0885d2533617d148fcab4f96", + "ai-engineering": "2fa0f168bfb8e1ba11edbcd5cdda2a6b150726f86d9c11e77ee26c21ce7fc887", + "docs/architecture.md": "d84f7716ce7ad7da107c41cfa0e453047f72ee8291991373c82175bf7e6b445c", + "docs/benchmarks/local-server-initial.json": "5a5df4ed04754cfe53ec4f18ded72dcd0821603601f1dd38f6188b80bb164bd6", + "docs/benchmarks/local-server-native.json": "c2091eac03c9c7d0fd1654ca38df679161bf9d0f1deee7231d51c4fd74ae43dd", + "docs/cli-adapters.md": "bbf42d7953cb3ff48e75f0ce2228d83afc87c5e10b69d02d555bcd25ca3e32e1", + "docs/compatibility.md": "c127cb6440f561a976b696af5b99a9659da124a7151c170de3413e40cd377cfc", + "docs/discussion-import.md": "de1e09cd8b576da796a6af7dd4b4c8bac6ec08d8cf3c21389155b0710cf5ecda", + "docs/discussion-slice.md": "3aa8b75ddb6c7ba546740594d6709ba78fcffc553a63e0366cd6b56771eae1e5", + "docs/epics.md": "67ea357a91f1fbe64330b1b5a4fd26432e846bd687f961e23e3deca6cb23ceba", + "docs/experiments.md": "cf6ed18390d16f9483bb8a26f77b3ae040e1cabdc6570ab3300bb1bfb4cd2646", + "docs/latency-scenario.md": "5f4d5591b18d6694982396f82ea5c1112cc9a3ea1abd8335bfcf91d5d2a1acf6", + "docs/legacy-file-storage.md": "97613b0b58baf02f9c5ef31dfe95ee4b33ef742296c6d94ca3e660205b92d598", + "docs/local-server-results.md": "eee82ffe4cc7f4b631be89fe54d4a278e8a95ce74cd80981ec1396a4339a46a2", + "docs/local-server-sse.md": "2ecf3cc6feb85d53778f1441db43faf0e9bfbb7f7a48c3bc4f50fe93aac447a1", + "docs/local-server.md": "f726ca6c9ef65d3534ea6c9b69e8298f4207df255746ea254d1d12881e823628", + "docs/plan-consolidation.md": "9fdc22aab9975e46bb67b1b1aefab0e71af3f069762770662e590483ae1a68cc", + "docs/protocol.md": "c5bf6bf2d459312a3d92e477a1b43dcbdd86aa41c45bd5c10a314560df8a419a", + "docs/roadmap.md": "b3f7d396ad9c4a41a8a02136529f628febf53c4bf2b97acb331668efb76dbeff", + "docs/sqlite-migration-design.md": "21f775427602af06820e6fbeb4d08ff639c803bf923aa0277574df8b2a60488d", + "docs/storage-migration.md": "ac54b7bd2c963367a47d488a32c16720154243378e82b10ba3b78209c8d16aad", + "docs/work-guidance.md": "45e7934db455d427ac1374a1694707d8075ca80b63eef7e13b875e1531474562", + "libawt.dylib": "c794235bd609c8ce066aa3d5b2a3dd5b99d40b5fcd595aceddf4f54051be5d24", + "libawt_lwawt.dylib": "ff09e5e47be4b96c3560b42c890c851ff18e99ddf4d8085525a3244c0aeeba4e", + "libfontmanager.dylib": "3b33fb98dc2937c495ca7833396ad1d613e261e5b6164115821915353ddcdde4", + "libfreetype.dylib": "9a88ef02fe6522f024c2d1e2dee8c1dd053a8ab87d1f61d2b62ea1806b2b189d", + "libjava.dylib": "465aac4cf94ccbd19c4849b89c61284b459c648ecc0f813e8452ad8c6905f444", + "libjavajpeg.dylib": "9370b79daf271c2da78275baa782cfb987c49f0a554585fd35a9edf32211e716", + "libjvm.dylib": "d535b761c960e4f4d1867fc2a977dbc28f7d8fb2a32d7db9bf478c56c175b71d", + "liblcms.dylib": "8d554b5fdb043bb7daff0c305c4464e934387576cb64955b39889ff29a7b0c60", + "libmlib_image.dylib": "e7d5a248aa7956f476aaba2483d7e7684406c3eff3c3984a2a5bba4f9e05fb30", + "libosxapp.dylib": "18fbd74e41bad5e3cb4e6c1a212c75a9590aa863947d5edcdd3571aa5e550105", + "libsqlitejdbc.dylib": "47fa68b43f34552fbfedeed25e82875a42cfd53e81c33c7cee20ac3f729c060e", + "sqlite3": "440575f732a7ff117b604ddd87d742833685a3a6cb3faff414c258b87fc2204c" + } + } + }, + "baseline": { + "path": "/private/tmp/aie-wrk000e-baseline-package/ai-engineering", + "sha256": "ba200c28e3ddc6d78668aecf5587524d718902fc6c5eeb607bbca07ee8947658", + "version": "ai-engineering 0.1.0", + "roundtrip": { + "samples": 100, + "minMs": 245.154708, + "p50Ms": 248.1353335, + "p95Ms": 252.225, + "maxMs": 297.107416, + "rawMs": [ + 252.045584, + 248.051541, + 245.702, + 249.352958, + 247.76325, + 245.338459, + 247.057625, + 247.6025, + 249.966792, + 247.881167, + 248.051208, + 249.223959, + 248.307875, + 249.361166, + 248.009375, + 249.421042, + 249.524042, + 247.167375, + 248.129958, + 249.7405, + 252.521084, + 248.329208, + 249.882125, + 249.121459, + 248.769542, + 252.225, + 246.79025, + 247.251375, + 245.154708, + 245.525417, + 247.197541, + 248.008583, + 248.605166, + 246.947291, + 247.286542, + 247.399666, + 249.042459, + 247.314, + 247.341875, + 249.119292, + 246.808375, + 245.478875, + 245.816125, + 250.391458, + 247.9555, + 247.242916, + 251.236625, + 249.777958, + 248.468208, + 248.485791, + 247.744292, + 247.068625, + 248.588875, + 250.362041, + 248.637791, + 246.075208, + 249.188708, + 248.140709, + 249.313, + 248.675625, + 246.043625, + 247.238292, + 263.43525, + 257.094083, + 249.968959, + 248.012209, + 249.166709, + 249.219709, + 248.290792, + 248.350125, + 246.845125, + 248.723167, + 248.073958, + 248.776125, + 246.788958, + 251.191875, + 249.24725, + 246.333375, + 247.315334, + 246.071542, + 250.410042, + 249.084292, + 247.372958, + 246.984542, + 247.194083, + 247.142208, + 247.239875, + 246.797584, + 250.116083, + 252.378541, + 246.629417, + 248.9465, + 248.83925, + 247.309959, + 246.2065, + 297.107416, + 249.736625, + 247.423667, + 245.738166, + 248.331583 + ] + } + }, + "fixture": { + "version": "ai-engineering 0.1.0", + "binary": "/Users/niltonconstantino/personal/workspace.personal/intrepid/ai-engineering/build/native/package/ai-engineering", + "binarySha256": "0c360680bc0355bce8dedb3342d73aed73f0de7042ffe7c25755561b752f7ef7", + "platform": "macOS-27.2.1-arm64-arm-64bit", + "machine": "arm64", + "storage": "sqlite", + "works": 100, + "entriesPerWork": 10, + "selectedWork": "WRK-0064", + "measurementPerformed": false + }, + "readiness": { + "samples": 10, + "minMs": 279.354541, + "p50Ms": 284.5805415, + "p95Ms": 289.952334, + "maxMs": 289.952334, + "rawMs": [ + 289.952334, + 281.8995, + 285.948041, + 283.171875, + 286.641917, + 286.5895, + 283.213042, + 279.872959, + 289.282, + 279.354541 + ] + }, + "firstUse": { + "samples": 10, + "minMs": 110.338834, + "p50Ms": 114.1799375, + "p95Ms": 147.844083, + "maxMs": 147.844083, + "rawMs": [ + 120.2665, + 110.6965, + 110.883167, + 122.842125, + 112.405083, + 110.338834, + 147.844083, + 118.626958, + 115.954792, + 110.828666 + ] + }, + "warm": { + "samples": 100, + "minMs": 33.537625, + "p50Ms": 43.9224375, + "p95Ms": 52.730458, + "maxMs": 99.280542, + "rawMs": [ + 34.481667, + 36.241958, + 33.717791, + 35.211041, + 40.031291, + 51.585333, + 56.2185, + 58.282291, + 51.727625, + 49.40725, + 99.280542, + 49.367208, + 50.964584, + 56.786417, + 47.983667, + 50.743708, + 38.514916, + 40.215584, + 44.014792, + 41.886625, + 39.79825, + 42.414708, + 43.093042, + 42.825291, + 46.515458, + 47.277708, + 44.157292, + 52.114208, + 49.488041, + 42.305292, + 44.416167, + 52.090917, + 45.6385, + 49.675375, + 49.939, + 42.854958, + 46.137334, + 47.519917, + 39.545, + 41.859667, + 35.3645, + 37.961, + 40.782292, + 43.062916, + 48.203583, + 45.259792, + 50.854542, + 41.31675, + 40.385709, + 43.830083, + 36.761917, + 37.224792, + 36.573834, + 40.969125, + 68.0515, + 39.994833, + 41.051042, + 42.957333, + 42.428042, + 43.560542, + 48.143333, + 47.445042, + 44.286541, + 47.78575, + 45.193333, + 39.918917, + 40.87525, + 40.816459, + 47.281917, + 48.187, + 46.691584, + 48.802458, + 45.130208, + 52.730458, + 48.521458, + 48.77825, + 47.306333, + 49.6775, + 39.340042, + 40.246916, + 44.368917, + 46.550375, + 45.618875, + 42.819459, + 39.3795, + 45.284542, + 45.089958, + 42.67825, + 37.763958, + 35.98575, + 35.276709, + 33.537625, + 37.561958, + 38.99925, + 41.129208, + 39.546958, + 41.598334, + 43.69275, + 47.036291, + 46.059625 + ] + }, + "serverBaseline": { + "path": "/private/tmp/aie-sse-baseline-package/ai-engineering", + "sha256": "4764f522935d8fdb1600f5a925e845ddb62689a4743a9e17f8eb433347d1e8c2", + "package": { + "schemaVersion": 1, + "aieVersion": "0.1.0", + "protocolVersion": 4, + "sqliteVersion": "3.54.1", + "localServerProtocol": 1, + "buildIdentity": "79f2d2b1a929f76c59d3214ffe55a635e87ab9f536e3f8c28f88438f2a421747", + "files": { + "LICENSE": "975eef35ea2ca6532c53302a8bf202b99231cc7387ebbb022b1af1d58e4852b6", + "README.md": "584c14e6eb74928674c75d1778a692157f63723aad1f51b949dca1055e04f136", + "ai-engineering": "4764f522935d8fdb1600f5a925e845ddb62689a4743a9e17f8eb433347d1e8c2", + "docs/architecture.md": "64f6429677d8073f31d56882f42bed1fcab9820b1c6174026cf46149b90ffb5f", + "docs/cli-adapters.md": "bbf42d7953cb3ff48e75f0ce2228d83afc87c5e10b69d02d555bcd25ca3e32e1", + "docs/compatibility.md": "c127cb6440f561a976b696af5b99a9659da124a7151c170de3413e40cd377cfc", + "docs/discussion-import.md": "de1e09cd8b576da796a6af7dd4b4c8bac6ec08d8cf3c21389155b0710cf5ecda", + "docs/discussion-slice.md": "3aa8b75ddb6c7ba546740594d6709ba78fcffc553a63e0366cd6b56771eae1e5", + "docs/epics.md": "67ea357a91f1fbe64330b1b5a4fd26432e846bd687f961e23e3deca6cb23ceba", + "docs/experiments.md": "cf6ed18390d16f9483bb8a26f77b3ae040e1cabdc6570ab3300bb1bfb4cd2646", + "docs/latency-scenario.md": "d98b5a16c00b6e97f2af33d736515252c39bfdb2ea0ca214c22efbba69ef1183", + "docs/legacy-file-storage.md": "97613b0b58baf02f9c5ef31dfe95ee4b33ef742296c6d94ca3e660205b92d598", + "docs/local-server.md": "26ab737dfa424a35eceffe25177a7b6b006e535e7ccf2c2df41eb97e69ad498e", + "docs/plan-consolidation.md": "9fdc22aab9975e46bb67b1b1aefab0e71af3f069762770662e590483ae1a68cc", + "docs/protocol.md": "c5bf6bf2d459312a3d92e477a1b43dcbdd86aa41c45bd5c10a314560df8a419a", + "docs/roadmap.md": "b3f7d396ad9c4a41a8a02136529f628febf53c4bf2b97acb331668efb76dbeff", + "docs/sqlite-migration-design.md": "21f775427602af06820e6fbeb4d08ff639c803bf923aa0277574df8b2a60488d", + "docs/storage-migration.md": "ac54b7bd2c963367a47d488a32c16720154243378e82b10ba3b78209c8d16aad", + "docs/work-guidance.md": "45e7934db455d427ac1374a1694707d8075ca80b63eef7e13b875e1531474562", + "libawt.dylib": "c794235bd609c8ce066aa3d5b2a3dd5b99d40b5fcd595aceddf4f54051be5d24", + "libawt_lwawt.dylib": "ff09e5e47be4b96c3560b42c890c851ff18e99ddf4d8085525a3244c0aeeba4e", + "libfontmanager.dylib": "3b33fb98dc2937c495ca7833396ad1d613e261e5b6164115821915353ddcdde4", + "libfreetype.dylib": "9a88ef02fe6522f024c2d1e2dee8c1dd053a8ab87d1f61d2b62ea1806b2b189d", + "libjava.dylib": "465aac4cf94ccbd19c4849b89c61284b459c648ecc0f813e8452ad8c6905f444", + "libjavajpeg.dylib": "9370b79daf271c2da78275baa782cfb987c49f0a554585fd35a9edf32211e716", + "libjvm.dylib": "d535b761c960e4f4d1867fc2a977dbc28f7d8fb2a32d7db9bf478c56c175b71d", + "liblcms.dylib": "8d554b5fdb043bb7daff0c305c4464e934387576cb64955b39889ff29a7b0c60", + "libmlib_image.dylib": "e7d5a248aa7956f476aaba2483d7e7684406c3eff3c3984a2a5bba4f9e05fb30", + "libosxapp.dylib": "18fbd74e41bad5e3cb4e6c1a212c75a9590aa863947d5edcdd3571aa5e550105", + "libsqlitejdbc.dylib": "47fa68b43f34552fbfedeed25e82875a42cfd53e81c33c7cee20ac3f729c060e", + "sqlite3": "440575f732a7ff117b604ddd87d742833685a3a6cb3faff414c258b87fc2204c" + } + }, + "roundtrip": { + "samples": 100, + "minMs": 35.376542, + "p50Ms": 50.244063, + "p95Ms": 56.969417, + "maxMs": 60.157083, + "rawMs": [ + 42.715416, + 39.09525, + 38.239209, + 37.035166, + 37.447917, + 39.666, + 41.215583, + 45.441875, + 47.381792, + 46.277791, + 48.657334, + 52.255459, + 47.425167, + 50.080083, + 57.620042, + 54.5475, + 51.618916, + 48.505875, + 46.306958, + 53.5165, + 51.731833, + 51.088667, + 47.873125, + 51.439334, + 52.454333, + 53.671583, + 48.833541, + 55.405333, + 50.291584, + 50.477709, + 55.7595, + 49.025541, + 51.199458, + 49.88725, + 55.038583, + 60.157083, + 52.494875, + 54.252292, + 56.969417, + 54.592458, + 49.5385, + 54.764916, + 54.187416, + 54.269625, + 54.390375, + 48.321416, + 53.511042, + 59.531208, + 49.600208, + 49.828584, + 52.10675, + 42.941834, + 42.966208, + 42.001584, + 48.53, + 53.9495, + 49.582875, + 57.546792, + 53.727834, + 58.162792, + 54.521667, + 47.934875, + 49.674209, + 56.507, + 48.376917, + 51.598292, + 51.293416, + 52.109375, + 53.021542, + 48.891875, + 53.835333, + 50.164333, + 50.185334, + 50.196542, + 45.999125, + 52.37525, + 51.912958, + 47.918292, + 48.870417, + 54.110667, + 50.764125, + 42.50375, + 42.017959, + 43.11375, + 35.376542, + 38.646292, + 41.034875, + 40.318333, + 42.526875, + 46.629167, + 45.452791, + 49.651583, + 53.920833, + 51.994417, + 50.58725, + 50.946959, + 48.99525, + 52.794167, + 54.237625, + 55.123417 + ] + } + }, + "memory": [ + { + "projects": 1, + "processes": [ + { + "pid": 45168, + "rssMiB": 48.609375 + } + ], + "totalRssMiB": 48.609375 + }, + { + "projects": 5, + "processes": [ + { + "pid": 45168, + "rssMiB": 48.640625 + }, + { + "pid": 45177, + "rssMiB": 48.453125 + }, + { + "pid": 45185, + "rssMiB": 48.546875 + }, + { + "pid": 45192, + "rssMiB": 48.515625 + }, + { + "pid": 45199, + "rssMiB": 48.46875 + } + ], + "totalRssMiB": 242.625 + }, + { + "projects": 10, + "processes": [ + { + "pid": 45168, + "rssMiB": 48.6875 + }, + { + "pid": 45177, + "rssMiB": 48.484375 + }, + { + "pid": 45185, + "rssMiB": 48.578125 + }, + { + "pid": 45192, + "rssMiB": 48.546875 + }, + { + "pid": 45199, + "rssMiB": 48.5 + }, + { + "pid": 45216, + "rssMiB": 48.53125 + }, + { + "pid": 45224, + "rssMiB": 48.46875 + }, + { + "pid": 45231, + "rssMiB": 48.4375 + }, + { + "pid": 45238, + "rssMiB": 48.578125 + }, + { + "pid": 45247, + "rssMiB": 48.515625 + } + ], + "totalRssMiB": 485.328125 + } + ], + "acceptance": { + "warmP95AtMost100Ms": true, + "allReadinessAtMost1000Ms": true + } +} diff --git a/docs/latency-scenario.md b/docs/latency-scenario.md index 866d54f..2fc6b09 100644 --- a/docs/latency-scenario.md +++ b/docs/latency-scenario.md @@ -1,6 +1,9 @@ -# WRK-000C measurement handoff +# Historical WRK-000C measurement handoff -SQLite adoption does not close the latency ticket. This scenario prepares comparable +WRK-000C was cancelled by Nilton; WRK-000E implements the local-server model and +records [native SSE measurements](local-server-sse-results.md). The scenario below preserves +the earlier backend-comparison handoff; it is not the accepted server benchmark. +SQLite adoption alone did not establish latency results. This scenario prepares comparable local datasets; it makes no performance claim and was not run as a benchmark in WRK-000D. Use the same final executable/package, machine and source revision for both backends. Keep companion libraries beside the executable. @@ -31,5 +34,5 @@ Use no registered Git repositories first, then measure their contribution separa Do not mix migration, integrity repair, network/provider calls or fixture generation into query timing. The current physical native verification used macOS arm64 and GraalVM CE 25.5.5.0+3 with SQLite JDBC 3.54.1.0 / sqlite3 3.54.1; other machines need -their own recorded environment. WRK-000C remains OPEN until actual measurements and -responsiveness criteria justify its decision and implementation. +their own recorded environment. The historical instructions do not reopen WRK-000C +or replace WRK-000E's accepted scenario and measured results. diff --git a/docs/local-server-results.md b/docs/local-server-results.md new file mode 100644 index 0000000..30b3984 --- /dev/null +++ b/docs/local-server-results.md @@ -0,0 +1,78 @@ +# Native local-server measurements + +These historical PLN-0001 measurements cover the initial polling implementation. +The delivered SSE implementation is measured separately in [SSE results](local-server-sse-results.md). + +WRK-000E / PLN-0001 measured on 2026-11-22, Apple M2 Pro (10 logical CPUs), +16 GiB RAM, macOS 27.2.1 arm64. Native GraalVM CE 25.5.5.0+3, Java 25, +Spring Boot 4.0.9 and SQLite JDBC 3.54.1.0. These are observations on this machine. + +| Operation | Samples | Median | p95 | Maximum | +|---|---:|---:|---:|---:| +| Fresh native client, ready server, `work show` | 100 | 35.22 ms | 41.14 ms | 42.38 ms | +| Manual `start` through readiness | 10 | 285.55 ms | 291.38 ms | 291.38 ms | +| Automatic first `work show`, server stopped | 10 | 111.27 ms | 113.50 ms | 113.50 ms | +| Preserved native baseline, Spring per invocation | 100 | 252.97 ms | 261.32 ms | 304.63 ms | + +Both accepted targets passed: ready-server p95 <=100 ms and readiness <=1 second +in every measured start. The ready-server p95 was about 6.4 times faster than the +baseline. The baseline is the complete native package preserved before this Work, +not a JVM comparison. No Rust implementation or DI migration was benchmarked. + +The initial server implementation failed: ready-server p95 was 652.35 ms. +Constructing the entire annotated Picocli command graph repeatedly dominated the +cost. The implementation now parses prefixes with Picocli and constructs only +the selected branch, with fresh command objects; full catalogs remain available +for help and unknown-command diagnostics. EXP-0001 records the refutation and +EXP-0002 records the reconsideration and successful repeat. + +The dataset contains 100 synthetic Works and 10 notes per Work in SQLite, created +through public commands. No Git repository or provider/network activity is involved. +The second experiment copied the stopped original fixture without operational server +state. Each timed query checked that its JSON matched the baseline. Ten ready-server +warmups preceded 100 independent client processes. Times use Python's monotonic +clock, include process launch/transport/queue/operation/output capture, and exclude +terminal rendering. p95 uses nearest rank. Process-cold starts do not flush OS caches. +Manual `start` includes its management parser; automatic first use takes a shorter +path. Server readiness alone does not promise a particular application's operation cost. + +After a fresh start and one `work show` per server, summed resident memory was: + +| Active project servers | Total process RSS | +|---|---:| +| 1 | 48.52 MiB | +| 5 | 242.69 MiB | +| 10 | 485.47 MiB | + +The first project contains the nominal dataset; the additional projects contain one +Work each. RSS is an idle snapshot after that read, not peak memory or proportional +memory; shared pages can be counted repeatedly. Large outputs and provider jobs +need separate workload measurements. All fixture servers were stopped afterward. + +Raw samples, initial load average, package component hashes, binary paths and fixture +provenance are retained in [the accepted run](benchmarks/local-server-native.json) +and [the initial run](benchmarks/local-server-initial.json). The accepted build ID is +`79f2d2b1a929f76c59d3214ffe55a635e87ab9f536e3f8c28f88438f2a421747`; +native binary SHA-256 is +`4764f522935d8fdb1600f5a925e845ddb62689a4743a9e17f8eb433347d1e8c2`. + +To reproduce with new disposable directories and a preserved baseline package: + +```sh +python3 scripts/server-benchmark.py \ + --binary build/native/package/ai-engineering \ + --baseline /path/to/preserved-package/ai-engineering \ + --directory /tmp/aie-server-benchmark-new \ + --output /tmp/aie-server-benchmark-new.json --samples 100 --starts 10 +``` + +Fixture generation is separate from timed operations. `--fixture PATH` can copy a +previously generated, stopped synthetic dataset. A failed target returns nonzero; +the script still retains its results and stops the disposable servers. + +Verification at the PLN-0001 checkpoint: `./gradlew check` passed 248 tests with no +failures or skips and the 11 Jenkins pipeline fixture scenarios. The complete +native smoke, native package verifier and 17 disposable installer tests passed. +Work/project integrity, shell/Python syntax, documentation links and diff checks +passed. Fixture servers were stopped. The measured binary/build hashes still +matched that checkpoint's candidate package; the active user installation was not changed. diff --git a/docs/local-server-sse-results.md b/docs/local-server-sse-results.md new file mode 100644 index 0000000..e287d92 --- /dev/null +++ b/docs/local-server-sse-results.md @@ -0,0 +1,103 @@ +# Native SSE results + +WRK-000E / DEC-0002 / PLN-0002 measured on 2026-11-22, Apple M2 Pro, 10 logical +CPUs, 16 GiB RAM, macOS 27.2.1 arm64. GraalVM CE 25.5.5.0+3 / Java 25, +Spring Boot 4.0.9 and SQLite JDBC 3.54.1.0 remain unchanged. No Rust port, DI +migration or JDBC pool is part of this change. + +| Operation | Samples | Median | p95 | Maximum | +|---|---:|---:|---:|---:| +| Fresh client, ready server, `work show` | 100 | 43.92 ms | 52.73 ms | 99.28 ms | +| Manual `start` to readiness | 10 | 284.58 ms | 289.95 ms | 289.95 ms | +| Automatic first `work show`, server stopped | 10 | 114.18 ms | 147.84 ms | 147.84 ms | +| Preserved server before SSE, same records | 100 | 50.24 ms | 56.97 ms | 60.16 ms | +| Preserved native Spring-per-call baseline | 100 | 248.14 ms | 252.23 ms | 297.11 ms | +| Queries with four waiting SSE jobs | 100 | 44.94 ms | 55.18 ms | 62.78 ms | + +The <=100 ms ready-server p95 and <=1 second readiness targets passed. These are +sequential runs on this machine, not randomized causal comparisons. SSE improves +ongoing event delivery; it does not itself establish a bootstrap speedup. + +The pure-query dataset remains 100 synthetic Works and 1,000 notes, SQLite, without +Git, providers or external network. It is copied from the stopped fixture originally +created through public CLI commands; operational server state is excluded. Ten warmups +precede 100 independent native clients. Python's monotonic clock includes launch, +transport, queue, command execution and captured output, excluding terminal rendering. +p95 uses nearest rank. Process-cold starts leave OS file caches intact. Manual +management commands still construct their full help-capable parser. + +The stream workload adds four surveys with ten questions each to WRK-0001 in a +separate copy of the same dataset. All four jobs subscribe before 100 fresh-client +queries of WRK-0064; they are waiting for input during those queries. The jobs then +answer concurrently, producing 40 input-to-next-output observations: + +| Stream workload | Result | +|---|---:| +| Responses verified | 40 / 40 | +| Input POST start to next output/event, median | 471.07 ms | +| Input POST start to next output/event, p95 | 537.23 ms | +| Input POST start to next output/event, maximum | 543.80 ms | +| Resident memory with four waiting streams, after setup | 63.70 MiB | + +That timing includes the control request, survey/history validation, publication and +writer contention. It is not isolated SSE transport latency. Unicode output matches +durable results, terminal snapshots after reconnect match, and a separate native job +verifies cooperative cancellation. Client tests count one submit and zero periodic +job GETs during ordinary reconnection. Ambiguous input responses use one recovery +lookup and preserve the buffered line/sequence. + +The first concurrent workload failed with `Project publication is busy; local writer +wait exceeded 2000 ms`. EXP-0001 retained partial evidence; EXP-0002 retained the +actual terminal error. The fix reuses only the validated bootstrap/backend choice +within each SQLite transaction, reducing repeated decoding while the publication +fence is held. It does not cache records across transactions, weaken domain/history +validation, infer SQLite from an existing database, change schema or enlarge timeouts. +EXP-0003 repeated the identical four-survey/40-answer workload successfully. + +After a fresh start and one `work show` per server, summed RSS was: + +| Project servers | Total process RSS | +|---|---:| +| 1 | 48.61 MiB | +| 5 | 242.62 MiB | +| 10 | 485.33 MiB | + +The first project has the nominal dataset; the rest have one Work each. These are +idle snapshots, not peak memory or proportional memory; shared pages can be counted +repeatedly. The four-stream RSS also includes mutation/setup allocations and job +state, so its difference cannot be attributed exclusively to SSE. Fixtures are stopped +and temporary stream projects removed afterward. + +Raw samples, environment/load, fixture provenance and component hashes are retained: +[nominal run](benchmarks/local-server-sse-native.json), +[stream run](benchmarks/local-server-sse-events.json), and +[failed stream run](benchmarks/local-server-sse-events-failed.json). +The measured build ID is `c891da8913045080a02d7b977a259d097e30864a5487e230d0ec7d5d4e78daff`; +native binary SHA-256 is `2fa0f168bfb8e1ba11edbcd5cdda2a6b150726f86d9c11e77ee26c21ce7fc887`. + +```sh +python3 scripts/server-benchmark.py \ + --binary build/native/package/ai-engineering \ + --baseline /path/to/native-per-call-package/ai-engineering \ + --server-baseline /path/to/pre-sse-package/ai-engineering \ + --directory /tmp/aie-sse-benchmark-new --output /tmp/aie-sse-benchmark-new.json \ + --samples 100 --starts 10 + +python3 scripts/native-sse-smoke.py \ + --binary build/native/package/ai-engineering \ + --fixture /tmp/aie-sse-benchmark-new/nominal \ + --samples 100 --questions 10 --streams 4 --output /tmp/aie-sse-events-new.json +``` + +Fixture generation is outside timing; `--fixture` can reuse a previously generated, +stopped synthetic dataset. The probe retains a failure diagnostic if a job fails, +cancels unfinished fixture jobs and attempts bounded shutdown during cleanup. + +Final verification: `./gradlew check` passed 269 tests without failures, errors or +skips and all 11 Jenkins pipeline fixture scenarios. The complete native smoke +passed on the final binary, including forced native SSE client execution, SQLite, +legacy formats, provider fixtures, authority, recovery and cancellation. The 17 +installer fixture tests, Work/project integrity, syntax, documentation links and +diff checks passed. Fixture servers were closed. The measured binary/build hashes +match the candidate; documentation synchronization changes package component hashes +without changing that executable. No active installation or consumer project was changed. diff --git a/docs/local-server-sse.md b/docs/local-server-sse.md new file mode 100644 index 0000000..5a0ec37 --- /dev/null +++ b/docs/local-server-sse.md @@ -0,0 +1,54 @@ +# SSE for pending invocations + +WRK-000E / DEC-0002 / PLN-0002 replaces repeated status requests with an event +subscription. `POST /execute` still admits one UUID/fingerprint exactly once under +the existing recovery contract. A terminal response stays ordinary JSON. Otherwise +the client opens `GET /requests/UUID/events`, authenticated with the same private +instance/protocol headers, and consumes `text/event-stream` as UTF-8. + +Frames have `id`, `event` and JSON `data` fields. The ID is a job generation UUID +and monotonic sequence joined by `:`. The payload contains the request `id`, event +`cursor`/`kind`, `stdoutOffset`/`stderrOffset`, incremental `stdout`/`stderr`, state, +exit code, input sequence, input requirement and cancellation flag. Output offsets +count UTF-16 characters, matching Java writers and the existing JSON response. + +Kinds are `snapshot`, `stdout`, `stderr`, `progress`, `input-required`, `completed` +and `unknown`. Output events carry deltas; state events carry no additional output. +A snapshot contains the complete retained output from offset zero. Its terminal +state can also represent a job that finished before subscription. Terminal events +follow durable receipt publication; UNKNOWN retains the existing ambiguous-outcome +semantics. Transient progress history is not a durable execution log. + +`Last-Event-ID` resumes within a generation. Replay is limited to 128 events and +256 Ki characters; output events use chunks of at most 16 Ki characters. A missing, +expired, future or different-generation cursor gets an explicit snapshot. The +client verifies previously received output before appending a snapshot suffix; +gaps or differing prefixes are errors, never silently accepted or replayed mutations. +After a crash only durable terminal output or an explicit UNKNOWN result is available. + +Publishers wake waiting subscribers when state/output changes. Waiting and replay +selection occur under the job monitor; socket writes happen after it is released. +No stream retains a database transaction or publication lock. An open subscription +does not itself count as job activity. Disconnecting it neither cancels the operation +nor resubmits `/execute`; input and cooperative cancellation remain explicit POSTs. + +`GET /requests/UUID` remains for inspection and recovery, rather than periodic +monitoring by the updated client. SSE is additive to local HTTP protocol 1; the +existing build-identity/drain lifecycle still selects matching client/server builds. +Engineering contract 4 and canonical SQLite memory are unchanged. + +The CLI allows three reconnect attempts with 100/200/400 ms backoff and a five-second +stream read timeout. A normal stream disconnect resumes from its last committed +cursor; an uncertain input response or a changed server instance also inspects the +durable result once. Input already read from stdin is retained with its sequence. +Neither stream exhaustion nor disconnection automatically cancels the job. + +The dedicated stream executor admits at most 16 subscriptions per project and two +per job. Heartbeats run every second; a socket write blocked for two seconds is +interrupted, closing its JDK SocketChannel. This detaches the subscriber and leaves +the job recoverable. Drain allows one second for terminal delivery once no jobs +remain, then closes remaining streams. These timers do not extend server idle time. + +Reference: [SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html). + +Native observations and reproduction commands: [SSE results](local-server-sse-results.md). diff --git a/docs/local-server.md b/docs/local-server.md new file mode 100644 index 0000000..198e9a8 --- /dev/null +++ b/docs/local-server.md @@ -0,0 +1,118 @@ +# Local project server + +WRK-000E / DEC-0001 separates process lifetime from command lifetime. The public +`aie` interface stays unchanged: a lightweight client discovers a project's server, +starts it when needed, and forwards literal arguments and the caller's working +directory. Spring starts only in the persistent server. Native GraalVM is the +distribution default; the same entry point supports a JVM for development. + +`aie start` waits for readiness and reuses a compatible running instance. `aie stop` +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. + +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 +instance identity, process, protocol/build identity, endpoint and capability token. +Clients authenticate and verify identity, and never infer ownership from a PID or +port alone. Startup is coordinated; incompatible versions drain before replacement. + +HTTP messages are versioned JSON. Commands are parsed with Picocli, not a shell. +Each request gets fresh parser, writers, reader and project context. No process-wide +working directory or standard streams are redirected. Output and errors remain +separate and the original exit code is returned. Interactive input is requested +only when the command reads it. Jobs expose progress, input, completion and +cooperative cancellation; a cancellation request never asserts rollback. + +Reads are bounded and concurrent. Writes are coordinated at their existing +transaction/lock boundaries; a provider call or an input prompt must not retain a +database transaction or monopolize the command executor. Native/file storage and +all human-authority checks retain their existing contracts. + +Mutations have a durable intent, request fingerprint and recoverable result in +private local operational state, separate from canonical engineering memory. +Repeated IDs cannot execute twice or change their arguments. A crash between +effects and a completed result leaves an explicitly unknown outcome, requiring +inspection rather than replay. This is not an exactly-once guarantee. Tokens, +credentials, environment dumps and transport logs are not canonical evidence. + +Acceptance targets on the recorded native test machine are p95 <= 100 ms for a +fresh client's `work show` roundtrip to a ready server, and <= 1 s from `aie start` +to readiness. The nominal disposable dataset has 100 Works and 10 notes per Work, +without Git or provider/network work. Record build hash, hardware, first use and +ready-server distributions, and memory at 1/5/10 active projects. These targets must +be measured; external framework benchmarks are not proof that AIE meets them. + +The native measurements now meet both targets on the recorded test machine. +See [current SSE results](local-server-sse-results.md) and the [earlier polling +measurements](local-server-results.md), including the initial failed implementation +and parser correction. + +## Operation and limits + +`aie server status` returns process status as JSON without starting a server. It +distinguishes STOPPED, STARTING, RUNNING and UNREACHABLE. `aie start` defaults to a +15-second readiness timeout; `aie stop` defaults to a 30-second drain timeout. +`--timeout-seconds N` overrides either. A stop timeout leaves the server draining; +active effects are not killed or rolled back. Changing the idle timeout with +`start --idle-timeout-seconds N` drains and replaces an existing instance when needed. +The override applies to that instance; a new automatic start defaults to 1,800 seconds. + +The server inherits the environment of the client that starts it. Restart it after +changing PATH, provider executables or environment-based credentials. Per-call cwd, +arguments, input and output are isolated; environment dumps are not forwarded or +stored in Work memory. Relative files resolve from the calling client's cwd. + +HTTP protocol 1 is independent of engineering contract 4. The instance listens only +on `127.0.0.1`, authenticates a private capability token, verifies instance identity +and rejects browser-origin requests. Startup and ownership use separate exclusive +OS locks. A stale descriptor without a lock owner can be replaced. A live but +unreachable owner is diagnosed rather than killed. Different compatible-protocol +builds drain before replacement; an unsupported protocol requires its matching CLI +to stop it. Ports can change after a restart. + +The protocol provides GET `/health`, POST `/execute`, GET `/requests/UUID`, GET +`/requests/UUID/events`, POST `/input`, POST `/cancel` and POST `/stop`. Requests contain the canonical project, +calling cwd, literal argv, UUID and console-input capability. Responses carry state, +stdout, stderr, exit code, input sequence and cancellation status. Input retries +reuse the same sequence. Operations report QUEUED, RUNNING, COMPLETED or UNKNOWN. +Pending invocations open an SSE subscription; immediate terminal responses stay +JSON. The client reports the request ID when opening the stream and progress every +five seconds while waiting. It does not poll job results. No execution is silently +resubmitted after an ambiguous connection loss. Input-response uncertainty and server +restart use a one-off result lookup, not periodic monitoring. + +SSE resumes with `Last-Event-ID`; expired cursors get an explicit snapshot. The +client checks overlaps and previously delivered prefixes before appending output. +After three reconnect attempts with 100/200/400 ms backoff, it reports the request +as recoverable and exits without cancelling/replaying it. The SSE read timeout is +five seconds and server heartbeats arrive every second. A crash can leave less +recoverable output than was already printed; a prefix gap is reported together +with the unknown outcome, never replaced silently. See [event framing and resource +bounds](local-server-sse.md). + +Four ordinary workers and a 64-entry queue handle short commands; up to four +dedicated workers handle provider jobs and guided survey input. Total active/queued +admission is bounded. An interactive wait or provider call does not retain a database +transaction. Writers keep the existing bounded SQLite/publication coordination. +SSE uses a separate executor with at most 16 streams per project and two per job. +Two-second blocked writes detach the subscriber; they do not cancel its job. +Streams/heartbeats alone do not postpone idle shutdown. Once jobs finish, drain +allows one second for terminal notification before closing remaining streams; +durable results remain available for recovery. + +JSON request bodies are limited to 1 MiB; accumulated output is limited to 8 MiB +characters per stream, with explicit failure on overflow. Response/receipt reads +are limited to 128 MiB. Large `work context`, input or provider workloads need their +own capacity assessment; the simple-query target does not cover them. + +`aie server request UUID` can start the server to inspect a durable result; +`aie server cancel UUID` addresses an existing server. Completed read results are +persisted too, so cache eviction does not lose a waiting client's output. Receipts +are private files containing fingerprints, outcomes and command output. They remain +after stop/restart and currently have no automatic pruning. Preserve receipts while +outcomes need recovery; removing them also removes their deduplication history. +Do not remove state while a server is running or an interrupted mutation is unresolved. +Canonical Works, decisions, approvals and evidence continue to belong to SQLite or +the selected legacy backend, not to these operational receipts. diff --git a/scripts/native-package-manifest.py b/scripts/native-package-manifest.py index b44d48d..d955a0c 100644 --- a/scripts/native-package-manifest.py +++ b/scripts/native-package-manifest.py @@ -8,5 +8,7 @@ package = Path(sys.argv[1]).resolve() files = {str(path.relative_to(package)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(package.rglob("*")) if path.is_file() and path.name != "aie-package.json"} manifest = {"schemaVersion": 1, "aieVersion": "0.1.0", "protocolVersion": 4, - "sqliteVersion": "3.54.1", "files": files} + "sqliteVersion": "3.54.1", "localServerProtocol": 1, "localServerEvents": "sse", + "buildIdentity": (Path(__file__).resolve().parents[1] / "build/generated/serverIdentity/aie-build.txt").read_text().strip(), + "files": files} (package / "aie-package.json").write_text(json.dumps(manifest, indent=2) + "\n") diff --git a/scripts/native-smoke.sh b/scripts/native-smoke.sh index a95a458..036b19b 100755 --- a/scripts/native-smoke.sh +++ b/scripts/native-smoke.sh @@ -5,7 +5,12 @@ set -euo pipefail aie_binary=${1:?Usage: native-smoke.sh /absolute/path/to/ai-engineering} aie_source_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) aie_fixture=$(mktemp -d "${TMPDIR:-/tmp}/ai-engineering-smoke.XXXXXX") -if [[ "${AIE_KEEP_FIXTURE:-0}" != 1 ]]; then trap 'rm -rf "$aie_fixture"' EXIT; fi +source "$aie_source_root/scripts/stop-fixture-servers.sh" +cleanup_native_fixture() { + stop_fixture_servers "$aie_fixture" "$aie_binary" || return 1 + if [[ "${AIE_KEEP_FIXTURE:-0}" != 1 ]]; then rm -rf "$aie_fixture"; fi +} +trap cleanup_native_fixture EXIT cd "$aie_fixture" "$aie_binary" --help > help.txt @@ -305,6 +310,8 @@ while [ "$#" -gt 0 ]; do shift done while IFS= read -r line; do :; done +# Make the synthetic provider pending long enough to exercise the native SSE client. +/bin/sleep 0.2 classification=0 case "$provider" in codex) while IFS= read -r line; do case "$line" in *'"activity"'*) classification=1;; esac; done < "$schema";; @@ -331,7 +338,8 @@ aie_without_git agent doctor --format json > doctor.json grep -q '"compatible" : true' doctor.json aie_without_git work create --mode DIRECT --approval WAIVED --human-approved --choice-reason "Explicit synthetic fixture policy" 'Provider protocol' > work.yaml aie_without_git discussion add WRK-0001 --text 'Synthetic source for provider protocol tests' > source.md -aie_without_git agent run WRK-0001 --task 'Summarize the synthetic note' --request-id classified --format json > codex.json +aie_without_git agent run WRK-0001 --task 'Summarize the synthetic note' --request-id classified --format json > codex.json 2> codex.stderr +grep -q '(SSE)' codex.stderr grep -q '"classification" : {' codex.json aie_without_git agent run WRK-0001 --activity analyze --task 'Continue from persisted context' --request-id reviewed --format json > claude.json grep -q '"transport" : "claude-cli"' claude.json @@ -627,3 +635,4 @@ if [[ "${AIE_KEEP_FIXTURE:-0}" == 1 ]]; then echo "Fixture retained: $aie_fixtur # Exercise the default SQLite backend, gates and migration separately from legacy fixtures. bash "$aie_source_root/scripts/native-sqlite-smoke.sh" "$aie_binary" +python3 "$aie_source_root/scripts/native-sse-smoke.py" --binary "$aie_binary" diff --git a/scripts/native-sqlite-smoke.sh b/scripts/native-sqlite-smoke.sh index 6dc7f8e..a302aab 100644 --- a/scripts/native-sqlite-smoke.sh +++ b/scripts/native-sqlite-smoke.sh @@ -3,7 +3,12 @@ set -euo pipefail binary=${1:?Usage: native-sqlite-smoke.sh /absolute/package/ai-engineering} source_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) fixture=$(mktemp -d "${TMPDIR:-/tmp}/aie-sqlite-smoke.XXXXXXXX") -trap 'rm -rf "$fixture"' EXIT +source "$source_root/scripts/stop-fixture-servers.sh" +cleanup_sqlite_fixture() { + stop_fixture_servers "$fixture" "$binary" || return 1 + rm -rf "$fixture" +} +trap cleanup_sqlite_fixture EXIT mkdir "$fixture/local" cd "$fixture/local" run() { PATH="$fixture/no-tools" "$binary" "$@"; } diff --git a/scripts/native-sse-smoke.py b/scripts/native-sse-smoke.py new file mode 100644 index 0000000..04852a2 --- /dev/null +++ b/scripts/native-sse-smoke.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +"""Exercise real native survey jobs over SSE in a disposable project; optionally measure the workload.""" +import argparse +import concurrent.futures +import hashlib +import http.client +import json +from pathlib import Path +import platform +import re +import shutil +import statistics +import subprocess +import tempfile +import threading +import time +import uuid + + +def distribution(samples): + ordered = sorted(samples) + import math + return {"samples": len(samples), "p50Ms": statistics.median(samples), + "p95Ms": ordered[math.ceil(len(samples) * .95) - 1], "maxMs": ordered[-1], "rawMs": samples} + + +def read_event(response): + data, cursor, kind, size = [], None, None, 0 + while True: + line = response.readline(128 * 1024 * 1024 + 1) + if not line: + raise RuntimeError("SSE ended before terminal notification") + size += len(line) + if size > 128 * 1024 * 1024: + raise RuntimeError("SSE frame exceeds limit") + line = line.decode("utf-8").rstrip("\r\n") + if not line: + if not data: + size = 0 + continue + event = json.loads("\n".join(data)) + if event["cursor"] != cursor or event["kind"] != kind: + raise RuntimeError("SSE frame identity mismatch") + return event + if line.startswith(":"): + continue + field, _, value = line.partition(":") + if value.startswith(" "): + value = value[1:] + if field == "id": + cursor = value + elif field == "event": + kind = value + elif field == "data": + data.append(value) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--samples", type=int, default=20) + parser.add_argument("--questions", type=int, default=3) + parser.add_argument("--streams", type=int, default=4) + parser.add_argument("--fixture", type=Path) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + if args.samples < 1 or args.questions < 1 or not 1 <= args.streams <= 4: + parser.error("Use positive samples/questions and 1..4 streams") + binary = args.binary.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="aie-native-sse-") as temporary: + root = Path(temporary).resolve() + + def cli(*command, directory=root): + result = subprocess.run([str(binary), *command], cwd=directory, text=True, capture_output=True, timeout=60) + if result.returncode: + raise RuntimeError("Native CLI failed: " + " ".join(command) + ": " + result.stderr) + return result.stdout + + gate, ready = threading.Event(), [threading.Event() for _ in range(args.streams)] + ids = [] + report = {"platform": platform.platform(), "binarySha256": hashlib.sha256(binary.read_bytes()).hexdigest(), + "buildIdentity": json.loads((binary.parent / "aie-package.json").read_text())["buildIdentity"], + "method": "Input POST start to first subsequent stdout/input/terminal SSE event, including command work and control response; no human think time.", + "concurrentStreams": args.streams, "questionsPerStream": args.questions} + try: + if args.fixture: + source = args.fixture.resolve(strict=True) + if json.loads(cli("server", "status", directory=source))["state"] != "STOPPED": + raise RuntimeError("Stop the synthetic fixture before copying") + shutil.copytree(source, root, dirs_exist_ok=True, ignore=shutil.ignore_patterns(".local")) + report["fixture"] = json.loads((root / "latency-fixture.json").read_text()) + query_work = "WRK-0064" + else: + cli("init", "--name", "Disposable native SSE verification") + cli("work", "create", "Synthetic SSE workload") + query_work = "WRK-0001" + work = "WRK-0001" + + def survey(count): + text = cli("survey", "create", work, "--title", "Synthetic SSE questions", "--author", "native-sse-fixture") + selected = re.search(r'\bid: "(SVY-\d+)"', text).group(1) + for index in range(count): + cli("survey", "question", work, selected, "--text", "Question " + str(index + 1) + " café 😀", + "--option", "One", "--option", "Two", "--author", "native-sse-fixture") + return selected + + surveys = [survey(args.questions) for _ in range(args.streams)] + endpoint = json.loads((root / ".ai-engineering/.local/server/endpoint.json").read_text()) + headers = {"Authorization": "Bearer " + endpoint["token"], "X-AIE-Instance": endpoint["instance"], + "X-AIE-Protocol": "1", "Content-Type": "application/json"} + + def rpc(method, path, body=None): + connection = http.client.HTTPConnection("127.0.0.1", endpoint["port"], timeout=10) + try: + connection.request(method, path, body=None if body is None else json.dumps(body).encode(), headers=headers) + response = connection.getresponse() + payload = response.read() + if response.status != 200: + raise RuntimeError("Native RPC failed: " + path + " HTTP " + str(response.status)) + return json.loads(payload) + finally: + connection.close() + + def submit(selected): + request_id = str(uuid.uuid4()) + view = rpc("POST", "/execute", {"id": request_id, "project": str(root), "cwd": str(root), + "argv": ["survey", "ask", work, selected, "--author", "native-sse-fixture"], "interactive": True}) + if view["state"] in ("COMPLETED", "UNKNOWN"): + raise RuntimeError("Interactive job finished before input") + return request_id + + def subscribe(request_id, cursor=None): + connection = http.client.HTTPConnection("127.0.0.1", endpoint["port"], timeout=10) + fields = dict(headers, Accept="text/event-stream") + if cursor: + fields["Last-Event-ID"] = cursor + connection.request("GET", "/requests/" + request_id + "/events", headers=fields) + response = connection.getresponse() + if response.status != 200 or not response.getheader("Content-Type", "").startswith("text/event-stream"): + connection.close() + raise RuntimeError("Native SSE subscription failed") + return connection, response + + def monitor(index, request_id): + connection, response = subscribe(request_id) + output = {"stdout": b"", "stderr": b""} + answered, latencies, events, pending = 0, [], 0, None + try: + while True: + event = read_event(response) + if event["id"] != request_id: + raise RuntimeError("Cross-request SSE output") + events += 1 + for stream in output: + text = event[stream].encode("utf-16-le", errors="surrogatepass") + offset = event[stream + "Offset"] * 2 + old = output[stream] + if offset > len(old) or (event["kind"] == "snapshot" and len(text) < len(old)): + raise RuntimeError("Native SSE output gap") + overlap = min(len(old) - offset, len(text)) + if old[offset:offset + overlap] != text[:overlap]: + raise RuntimeError("Native SSE output prefix changed") + output[stream] += text[overlap:] + if pending is not None and event["kind"] in ("stdout", "stderr", "input-required", "completed", "snapshot"): + latencies.append((time.perf_counter_ns() - pending) / 1_000_000) + pending = None + if event["state"] in ("COMPLETED", "UNKNOWN"): + if event["state"] != "COMPLETED" or event["exitCode"] != 0: + raise RuntimeError("Native SSE job failed: " + event["state"] + " exit=" + str(event["exitCode"]) + + " stderr=" + output["stderr"].decode("utf-16-le", errors="replace")[-2000:]) + break + if event["needsInput"] and event["inputSequence"] > answered: + ready[index].set() + if not gate.wait(60): + raise RuntimeError("SSE benchmark gate timed out") + answered = event["inputSequence"] + pending = time.perf_counter_ns() + rpc("POST", "/input", {"id": request_id, "sequence": answered, "text": "1\n"}) + if answered != args.questions or len(latencies) != args.questions: + raise RuntimeError("Native SSE input/event count mismatch") + if "café 😀" not in output["stdout"].decode("utf-16-le"): + raise RuntimeError("Native SSE Unicode prompt was not preserved") + saved = rpc("GET", "/requests/" + request_id) + for stream in output: + if output[stream].decode("utf-16-le") != saved[stream]: + raise RuntimeError("SSE output differs from durable result") + connection.close() + resumed, terminal = subscribe(request_id, event["cursor"]) + try: + snapshot = read_event(terminal) + if snapshot["kind"] != "snapshot" or snapshot["state"] != "COMPLETED" or snapshot["stdout"] != saved["stdout"]: + raise RuntimeError("Late native SSE result recovery failed") + finally: + resumed.close() + return {"events": events, "inputToEventMs": latencies, + "stdoutSha256": hashlib.sha256(output["stdout"]).hexdigest()} + finally: + connection.close() + + for selected in surveys: + ids.append(submit(selected)) + with concurrent.futures.ThreadPoolExecutor(max_workers=args.streams) as workers: + futures = [workers.submit(monitor, index, selected) for index, selected in enumerate(ids)] + try: + for index, signal in enumerate(ready): + if not signal.wait(15): + if futures[index].done(): + futures[index].result() + raise RuntimeError("Native SSE did not request input") + times = [] + for _ in range(5): + cli("work", "show", query_work, "--format", "json") + for _ in range(args.samples): + before = time.perf_counter_ns() + value = json.loads(cli("work", "show", query_work, "--format", "json")) + times.append((time.perf_counter_ns() - before) / 1_000_000) + if value["id"] != query_work: + raise RuntimeError("Query failed while SSE streams were active") + report["queriesWithStreams"] = distribution(times) + rss = int(subprocess.check_output(["/bin/ps", "-o", "rss=", "-p", str(endpoint["pid"])], text=True).strip()) + report["rssWithStreamsMiB"] = rss / 1024 + finally: + gate.set() + report["jobs"] = [future.result(timeout=60) for future in futures] + report["inputToEvent"] = distribution([sample for job in report["jobs"] for sample in job["inputToEventMs"]]) + + cancelled_id = submit(survey(1)) + ids.append(cancelled_id) + connection, response = subscribe(cancelled_id) + try: + while not read_event(response)["needsInput"]: + pass + rpc("POST", "/cancel", {"id": cancelled_id}) + while True: + event = read_event(response) + if event["state"] in ("COMPLETED", "UNKNOWN"): + if event["state"] != "COMPLETED" or event["exitCode"] == 0 or not event["cancellationRequested"]: + raise RuntimeError("Native SSE cancellation result invalid") + report["cancellationVerified"] = True + break + finally: + connection.close() + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print("Native SSE smoke passed: streaming, Unicode, input, concurrency, terminal recovery and cancellation.") + except BaseException as failure: + report["failure"] = str(failure) + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + raise + finally: + gate.set() + if "rpc" in locals(): + for request_id in ids: + try: + rpc("POST", "/cancel", {"id": request_id}) + except Exception: + pass # Cleanup still attempts the ordinary bounded stop below. + if (root / ".ai-engineering").exists(): + cli("stop", "--timeout-seconds", "10") + + +if __name__ == "__main__": + main() diff --git a/scripts/server-benchmark.py b/scripts/server-benchmark.py new file mode 100644 index 0000000..d64758e --- /dev/null +++ b/scripts/server-benchmark.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Measure disposable native clients/servers; never install or alter a real project.""" +import argparse +import datetime +import hashlib +import json +import math +import os +from pathlib import Path +import platform +import shutil +import statistics +import subprocess +import sys +import time + + +def distribution(samples): + ordered = sorted(samples) + return {"samples": len(samples), "minMs": ordered[0], "p50Ms": statistics.median(samples), + "p95Ms": ordered[math.ceil(len(samples) * .95) - 1], "maxMs": ordered[-1], "rawMs": samples} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--baseline", type=Path, required=True) + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--samples", type=int, default=100) + parser.add_argument("--starts", type=int, default=10) + parser.add_argument("--fixture", type=Path, help="Copy a previously generated, stopped synthetic fixture into the new directory.") + parser.add_argument("--server-baseline", type=Path, help="Also compare a preserved server package, such as the pre-SSE build.") + args = parser.parse_args() + if args.samples < 20 or args.starts < 5: + parser.error("Use at least 20 samples and 5 starts") + binary, baseline = args.binary.resolve(strict=True), args.baseline.resolve(strict=True) + root = args.directory.absolute() + root.mkdir(parents=True, exist_ok=False) + dataset = root / "nominal" + roots = [dataset] + + def run(directory, *command, executable=binary): + before = time.perf_counter_ns() + result = subprocess.run([str(executable), *command], cwd=directory, text=True, + capture_output=True, timeout=60) + elapsed = (time.perf_counter_ns() - before) / 1_000_000 + if result.returncode: + raise RuntimeError(f"{command}: exit {result.returncode}: {result.stderr}") + return result.stdout, elapsed + + def stop(directory): + if (directory / ".ai-engineering").exists(): + run(directory, "stop", "--timeout-seconds", "10") + + report = {"observedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "environment": {"platform": platform.platform(), "machine": platform.machine(), + "logicalCpus": os.cpu_count(), "initialLoadAverage": os.getloadavg()}, + "method": {"works": 100, "notesPerWork": 10, "storage": "sqlite", + "git": False, "provider": False, "freshClientPerSample": True, + "percentile": "nearest rank", "cold": "process cold; OS file caches not flushed"}, + "candidate": {"path": str(binary), "sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), + "package": json.loads((binary.parent / "aie-package.json").read_text())}, + "baseline": {"path": str(baseline), "sha256": hashlib.sha256(baseline.read_bytes()).hexdigest()}} + if sys.platform == "darwin": + for key, name in (("cpu", "machdep.cpu.brand_string"), ("physicalMemoryBytes", "hw.memsize")): + report["environment"][key] = subprocess.check_output(["/usr/sbin/sysctl", "-n", name], text=True).strip() + try: + if args.fixture: + source = args.fixture.resolve(strict=True) + status = json.loads(run(source, "server", "status")[0]) + if status["state"] != "STOPPED": + raise RuntimeError("Stop the synthetic source fixture before copying") + print("Copying the stopped synthetic dataset; operational server state excluded...", flush=True) + shutil.copytree(source, dataset, ignore=shutil.ignore_patterns(".local")) + report["method"]["copiedFixture"] = str(source) + else: + print("Generating 100 Works and 1,000 notes through the public CLI...", flush=True) + subprocess.run([sys.executable, str(Path(__file__).with_name("latency-fixture.py")), + "--binary", str(binary), "--directory", str(dataset), "--works", "100", "--entries", "10"], + check=True, stdout=subprocess.DEVNULL, timeout=1800) + report["fixture"] = json.loads((dataset / "latency-fixture.json").read_text()) + if report["fixture"]["works"] != 100 or report["fixture"]["entriesPerWork"] != 10: + raise RuntimeError("Expected the nominal 100 Work / 10 note fixture") + command = ("work", "show", "WRK-0064", "--format", "json") + report["method"]["command"] = list(command) + expected = json.loads(run(dataset, *command)[0]) + + def sample(executable=binary): + output, milliseconds = run(dataset, *command, executable=executable) + if json.loads(output) != expected: + raise RuntimeError("Benchmark output differs between invocations/builds") + return milliseconds + + print("Measuring process-cold readiness and automatic first use...", flush=True) + starts, first = [], [] + for _ in range(args.starts): + stop(dataset) + starts.append(run(dataset, "start")[1]) + stop(dataset) + first.append(sample()) + report["readiness"] = distribution(starts) + report["firstUse"] = distribution(first) + print("Measuring ready-server roundtrips...", flush=True) + for _ in range(10): + sample() + report["warm"] = distribution([sample() for _ in range(args.samples)]) + print("Measuring preserved per-call native baseline against identical records...", flush=True) + stop(dataset) + for _ in range(5): + sample(baseline) + report["baseline"]["version"] = run(dataset, "--version", executable=baseline)[0].strip() + report["baseline"]["roundtrip"] = distribution([sample(baseline) for _ in range(args.samples)]) + if args.server_baseline: + previous = args.server_baseline.resolve(strict=True) + print("Measuring the preserved server implementation on identical records...", flush=True) + run(dataset, "start", executable=previous) + try: + for _ in range(10): + sample(previous) + report["serverBaseline"] = {"path": str(previous), "sha256": hashlib.sha256(previous.read_bytes()).hexdigest(), + "package": json.loads((previous.parent / "aie-package.json").read_text()), + "roundtrip": distribution([sample(previous) for _ in range(args.samples)])} + finally: + run(dataset, "stop", "--timeout-seconds", "10", executable=previous) + + print("Measuring idle resident memory for 1/5/10 active projects...", flush=True) + run(dataset, "start") + sample() + report["method"]["memoryWorkload"] = "Fresh server then work show per project; first project has 100 Works/1000 notes, remaining projects one Work each. Summed process RSS, shared pages may be counted repeatedly." + report["memory"] = [] + for count in range(1, 11): + if count > 1: + project = root / ("project-" + str(count)) + project.mkdir() + roots.append(project) + run(project, "init", "--name", "Disposable memory project " + str(count)) + run(project, "work", "create", "One resident Work") + stop(project) + run(project, "start") + run(project, "work", "show", "WRK-0001", "--format", "json") + if count in (1, 5, 10): + time.sleep(1) + processes = [] + for project in roots: + status = json.loads(run(project, "server", "status")[0]) + if status["state"] != "RUNNING": + raise RuntimeError("Memory fixture server is not running") + pid = status["server"]["pid"] + rss_kib = int(subprocess.check_output(["/bin/ps", "-o", "rss=", "-p", str(pid)], text=True).strip()) + processes.append({"pid": pid, "rssMiB": rss_kib / 1024}) + report["memory"].append({"projects": count, "processes": processes, + "totalRssMiB": sum(item["rssMiB"] for item in processes)}) + report["acceptance"] = {"warmP95AtMost100Ms": report["warm"]["p95Ms"] <= 100, + "allReadinessAtMost1000Ms": report["readiness"]["maxMs"] <= 1000} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"warm": {k: v for k, v in report["warm"].items() if k != "rawMs"}, + "readiness": {k: v for k, v in report["readiness"].items() if k != "rawMs"}, + "acceptance": report["acceptance"]}, indent=2), flush=True) + return 0 if all(report["acceptance"].values()) else 1 + finally: + for project in reversed(roots): + stop(project) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/stop-fixture-servers.sh b/scripts/stop-fixture-servers.sh new file mode 100644 index 0000000..db0d920 --- /dev/null +++ b/scripts/stop-fixture-servers.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Source from a smoke script; stop only servers below that script's disposable root. +stop_fixture_servers() { + local fixture_root=$1 fixture_binary=$2 endpoint project + while IFS= read -r -d '' endpoint; do + project=${endpoint%/.ai-engineering/.local/server/endpoint.json} + "$fixture_binary" --project "$project" stop --timeout-seconds 10 >/dev/null || return 1 + done < <(find "$fixture_root" -type f -path '*/.ai-engineering/.local/server/endpoint.json' -print0) +} diff --git a/scripts/test-install-native.py b/scripts/test-install-native.py index d4b6496..3606902 100644 --- a/scripts/test-install-native.py +++ b/scripts/test-install-native.py @@ -52,11 +52,15 @@ printf '%s\n' "$PWD" "$JAVA_HOME" "$GRAALVM_HOME" "$@" >> "$FIXTURE_LOG" [[ "${FIXTURE_BUILD_EXIT:-0}" == 0 ]] || exit "$FIXTURE_BUILD_EXIT" [[ "${FIXTURE_MISSING_BINARY:-0}" == 0 ]] || exit 0 mkdir -p build/native/package +mkdir -p build/generated/serverIdentity +printf '%064d\\n' 0 > build/generated/serverIdentity/aie-build.txt cat > build/native/package/ai-engineering <<'EOF' #!/bin/bash case "${1:-}" in --version) echo "ai-engineering 0.1.0" ;; init) mkdir -p .ai-engineering; touch .ai-engineering/aie.db ;; + server) printf '{"state":"RUNNING","server":{"protocol":1,"build":"%064d"}}\\n' 0 ;; + work) [[ "${2:-}" != show ]] || echo '{"id":"WRK-0001"}' ;; *) echo "fixture CLI" ;; esac exit "${FIXTURE_BINARY_EXIT:-0}" @@ -69,6 +73,8 @@ EOF chmod +x build/native/package/sqlite3 if [[ "${FIXTURE_MISSING_LIBRARY:-0}" == 0 ]]; then echo "fixture library" > build/native/package/libsqlitejdbc.so; fi python3 scripts/native-package-manifest.py build/native/package +# This installer fixture models the earlier JSON-only server package, without real sockets. +python3 -c 'import json; from pathlib import Path; p=Path("build/native/package/aie-package.json"); m=json.loads(p.read_text()); m.pop("localServerEvents",None); p.write_text(json.dumps(m))' if [[ "${FIXTURE_CORRUPT_PACKAGE:-0}" == 1 ]]; then echo "changed" >> build/native/package/libsqlitejdbc.so; fi ''') diff --git a/scripts/verify-native-package.py b/scripts/verify-native-package.py index 615afe1..6c1c375 100644 --- a/scripts/verify-native-package.py +++ b/scripts/verify-native-package.py @@ -11,6 +11,10 @@ package = Path(sys.argv[1]).resolve() manifest = json.loads((package / "aie-package.json").read_text()) if manifest.get("schemaVersion") != 1 or manifest.get("protocolVersion") != 4: raise SystemExit("Unsupported native package manifest") +if manifest.get("localServerProtocol") not in (None, 1): + raise SystemExit("Unsupported local server protocol") +if manifest.get("localServerEvents") not in (None, "sse"): + raise SystemExit("Unsupported local server event transport") expected = manifest["files"] actual = set() for path in package.rglob("*"): @@ -41,4 +45,26 @@ with tempfile.TemporaryDirectory(prefix="aie-package-check-") as temporary: result = subprocess.check_output([str(sqlite), "-readonly", str(database), "PRAGMA quick_check;"], text=True).strip() if result != "ok": raise SystemExit("Packaged SQLite cannot read the native AIE database") + if manifest.get("localServerProtocol") == 1: + try: + subprocess.run([str(aie), "start"], cwd=root, check=True, stdout=subprocess.DEVNULL, timeout=20) + status = json.loads(subprocess.check_output([str(aie), "server", "status"], cwd=root, text=True, timeout=10)) + if status["state"] != "RUNNING" or status["server"]["protocol"] != 1 or status["server"]["build"] != manifest["buildIdentity"]: + raise SystemExit("Native server build/protocol mismatch") + subprocess.run([str(aie), "work", "create", "Disposable server verification"], cwd=root, + check=True, stdout=subprocess.DEVNULL, timeout=20) + work = json.loads(subprocess.check_output([str(aie), "work", "show", "WRK-0001", "--format", "json"], cwd=root, text=True, timeout=20)) + if work["id"] != "WRK-0001": + raise SystemExit("Native client/server roundtrip failed") + except BaseException: + log = root / ".ai-engineering/.local/server/startup.log" + if log.is_file(): + print(log.read_text()[-12000:], file=sys.stderr) + raise + finally: + 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-sse-smoke.py")), + "--binary", str(aie)], check=True, timeout=120) print("Native package verified:", package) diff --git a/src/main/java/net/intrepid/aiengineering/AiEngineeringApplication.java b/src/main/java/net/intrepid/aiengineering/AiEngineeringApplication.java index 6ecd3db..10eeb10 100644 --- a/src/main/java/net/intrepid/aiengineering/AiEngineeringApplication.java +++ b/src/main/java/net/intrepid/aiengineering/AiEngineeringApplication.java @@ -8,11 +8,22 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ImportRuntimeHints; import java.io.PrintWriter; import java.nio.file.Path; +import net.intrepid.aiengineering.localserver.*; @SpringBootApplication(proxyBeanMethods = false) @ImportRuntimeHints(NativeHints.class) public class AiEngineeringApplication { @Bean EngineeringCli engineeringCli() { return new EngineeringCli(Path.of("")); } + public static void serve(Path root, long idleMillis, ServerProtocol.Operations operations) throws InterruptedException { + var application = new SpringApplication(AiEngineeringApplication.class); + application.setMainApplicationClass(AiEngineeringApplication.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setDefaultProperties(java.util.Map.of("spring.main.banner-mode", "off", + "spring.main.log-startup-info", "false", "logging.level.root", "ERROR")); + try (var context = application.run(); var server = new ProjectServer(new ServerState(root), idleMillis, operations)) { + server.await(); + } + } public static void main(String[] args) { var application = new SpringApplication(AiEngineeringApplication.class); application.setWebApplicationType(WebApplicationType.NONE); diff --git a/src/main/java/net/intrepid/aiengineering/AieLauncher.java b/src/main/java/net/intrepid/aiengineering/AieLauncher.java new file mode 100644 index 0000000..7b2fac8 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/AieLauncher.java @@ -0,0 +1,29 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.filesystem.ProtocolException; +import net.intrepid.aiengineering.project.ProjectService; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; + +/** Distribution entry point. Spring's separate application main remains available to AOT tooling. */ +public final class AieLauncher { + private AieLauncher() {} + public static void main(String[] args) { + int code; + try { + if (args.length > 0 && args[0].equals(ServerLaunch.INTERNAL)) { + if (args.length != 3) throw ProtocolException.invalid("Internal server launch requires project and idle timeout"); + Path root = new ProjectService().discover(Path.of(args[1]), null); + AiEngineeringApplication.serve(root, Long.parseLong(args[2]), new RequestJobs(new ServerState(root))); + return; + } + code = new LocalClient(Path.of(""), new InputStreamReader(System.in, StandardCharsets.UTF_8), + new PrintWriter(System.out, true), new PrintWriter(System.err, true), System.console() != null).execute(args); + } catch (ProtocolException failure) { System.err.println(failure.getMessage()); code=failure.exitCode(); } + catch (InterruptedException failure) { Thread.currentThread().interrupt(); System.err.println("AIE interrupted"); code=4; } + catch (Exception failure) { System.err.println("AIE failed: " + failure.getMessage()); code=1; } + System.exit(code); + } +} diff --git a/src/main/java/net/intrepid/aiengineering/NativeHints.java b/src/main/java/net/intrepid/aiengineering/NativeHints.java index 3d373b8..459e926 100644 --- a/src/main/java/net/intrepid/aiengineering/NativeHints.java +++ b/src/main/java/net/intrepid/aiengineering/NativeHints.java @@ -11,10 +11,14 @@ import net.intrepid.aiengineering.agent.*; import net.intrepid.aiengineering.verification.*; import net.intrepid.aiengineering.legacyimport.DiscussionImport; import org.springframework.aot.hint.*; +import net.intrepid.aiengineering.localserver.*; public final class NativeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader loader) { - for (Class type : new Class[]{ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class, + for (Class type : new Class[]{ServerState.Descriptor.class, ServerProtocol.Request.class, + ServerProtocol.Health.class, ServerProtocol.View.class, ServerProtocol.Event.class, ServerProtocol.Input.class, + ServerProtocol.Cancel.class, ServerProtocol.Error.class, RequestJobs.Receipt.class, + ServerManager.Status.class, ProjectConfig.class, ProjectConfig.Identity.class, ProjectConfig.Repository.class, ProjectConfig.Access.class, ProjectService.Revision.class, Work.class, WorkService.Sequence.class, DiscussionEntry.class, Decision.class, Decision.Approval.class, Decision.ApprovalOrigin.class, Plan.class, Plan.Step.class, Plan.Exclusion.class, net.intrepid.aiengineering.work.WorkGuidance.class, net.intrepid.aiengineering.work.WorkGuidance.Choice.class, @@ -48,5 +52,6 @@ public final class NativeHints implements RuntimeHintsRegistrar { } hints.resources().registerPattern("protocol/*"); hints.resources().registerPattern("sqlite/*"); + hints.resources().registerPattern("aie-build.txt"); } } diff --git a/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java b/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java index 5143bb7..b621287 100644 --- a/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java +++ b/src/main/java/net/intrepid/aiengineering/cli/EngineeringCli.java @@ -30,10 +30,74 @@ public final class EngineeringCli implements Runnable { @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) { + public 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) { + int result = commandLineFor(out, err, args).execute(args); out.flush(); err.flush(); return result; + } + /** Parse prefixes with Picocli and inspect only the selected branch. Full catalogs remain available for help/errors. */ + public CommandLine commandLineFor(PrintWriter out, PrintWriter err, String... args) { + var spec = CommandLine.Model.CommandSpec.wrapWithoutInspection(this).name("ai-engineering") + .version("ai-engineering " + ProtocolContract.CLI_VERSION).mixinStandardHelpOptions(true); + spec.usageMessage().description("Portable engineering protocol for humans and AI agents."); + spec.addOption(CommandLine.Model.OptionSpec.builder("--project").type(Path.class).scopeType(ScopeType.INHERIT) + .description("Engineering project root or .ai-engineering directory.") + .setter(new CommandLine.Model.ISetter() { + @SuppressWarnings("unchecked") public T set(T value) { Path previous=project; project=(Path)value; return (T)previous; } + }).build()); + var parser = new CommandLine(spec).setStopAtUnmatched(true); + CommandLine branch=parser; + try { + while (true) { + var parsed=parser.parseArgs(args); + while (parsed.subcommand()!=null) parsed=parsed.subcommand(); + var unmatched=parsed.unmatched(); + if (unmatched.isEmpty()) return commandLine(out,err); + String name=unmatched.getFirst(); Object owner=branch.getCommandSpec().userObject(); + Object child=selectedGroup(owner,name); + if (child!=null) { + var metadata=child.getClass().getAnnotation(Command.class); + var childSpec=CommandLine.Model.CommandSpec.wrapWithoutInspection(child) + .name(metadata.name()).mixinStandardHelpOptions(true); + childSpec.usageMessage().description(metadata.description()); + var nested=new CommandLine(childSpec).setStopAtUnmatched(true); + branch.addSubcommand(name,nested); branch=nested; continue; + } + if (owner instanceof ImportCommands && name.equals("discussion")) { + branch.addSubcommand(name,new DiscussionImportCommand()); + } else { + var method=java.util.Arrays.stream(owner.getClass().getDeclaredMethods()) + .filter(value -> value.isAnnotationPresent(Command.class)) + .filter(value -> { var annotation=value.getAnnotation(Command.class); + return annotation.name().equals(name) || List.of(annotation.aliases()).contains(name); }) + .findFirst().orElse(null); + if (method==null) return commandLine(out,err); + branch.addSubcommand(name,new CommandLine(method)); + } + output=out; commandLine=parser; + resetPrefixParsing(parser); configureExecution(parser,out,err); return parser; + } + } catch (CommandLine.ParameterException invalidPrefix) { return commandLine(out,err); } + } + private Object selectedGroup(Object owner,String name) { + if (owner==this) return switch(name) { + case "project" -> new ProjectCommands(); case "repo" -> new RepoCommands(); case "work" -> new WorkCommands(); + 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; + }; + if (owner instanceof PlanCommands) return switch(name) { + case "step" -> new StepCommands(); case "experiment" -> new ExperimentCommands(); default -> null; + }; + return null; + } + private void resetPrefixParsing(CommandLine parser) { + parser.setStopAtUnmatched(false); parser.getSubcommands().values().forEach(this::resetPrefixParsing); + } + /** A fresh parser and command graph for one invocation. Parsing never executes a command. */ + public CommandLine commandLine(PrintWriter out, PrintWriter err) { output = out; commandLine = new CommandLine(this) .addSubcommand("project", new ProjectCommands()).addSubcommand("repo", new RepoCommands()) @@ -43,14 +107,18 @@ public final class EngineeringCli implements Runnable { .addSubcommand("topic", new TopicCommands()).addSubcommand("survey", new SurveyCommands()).addSubcommand("agent", new AgentCommands()) .addSubcommand("epic", new EpicCommands()).addSubcommand("gate", new GateCommands()).addSubcommand("storage", new StorageCommands()); commandLine.addSubcommand("import", new CommandLine(new ImportCommands()).addSubcommand("discussion", new DiscussionImportCommand())); - configure(commandLine, out, err); - commandLine.setExecutionExceptionHandler((exception, command, parse) -> { + configureExecution(commandLine,out,err); + return commandLine; + } + private void configureExecution(CommandLine parser, PrintWriter out, PrintWriter err) { + configure(parser, out, err); + parser.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; } + public Path selectedRoot() { return discoveredRoot(); } 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)); diff --git a/src/main/java/net/intrepid/aiengineering/filesystem/Filespace.java b/src/main/java/net/intrepid/aiengineering/filesystem/Filespace.java index d671164..a3686a3 100644 --- a/src/main/java/net/intrepid/aiengineering/filesystem/Filespace.java +++ b/src/main/java/net/intrepid/aiengineering/filesystem/Filespace.java @@ -12,6 +12,7 @@ import static java.nio.file.StandardOpenOption.*; /** Filesystem operations shared by the protocol adapters. Never executes project commands. */ public final class Filespace { private static final ThreadLocal> HELD = ThreadLocal.withInitial(java.util.HashSet::new); + private static final java.util.concurrent.ConcurrentHashMap LOCAL_WRITERS = new java.util.concurrent.ConcurrentHashMap<>(); private Filespace() {} @FunctionalInterface public interface IoSupplier { T get() throws IOException; } public static T io(IoSupplier action) { @@ -86,7 +87,14 @@ public final class Filespace { Path lock = resolve(projectRoot, ".ai-engineering/.local/write.lock"); if (HELD.get().contains(lock)) return operation.get(); directory(lock.getParent()); - return io(() -> { + var local = LOCAL_WRITERS.computeIfAbsent(lock, ignored -> new java.util.concurrent.locks.ReentrantLock(true)); + try { + if (!local.tryLock(SqliteDatabase.DEFAULT_BUSY_MILLIS, java.util.concurrent.TimeUnit.MILLISECONDS)) + throw ProtocolException.validation("Project publication is busy; local writer wait exceeded 2000 ms"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); throw ProtocolException.validation("Interrupted while waiting for project publication"); + } + try { return io(() -> { try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = acquire(channel, bounded)) { HELD.get().add(lock); try { return operation.get(); } @@ -94,7 +102,7 @@ public final class Filespace { } catch (java.nio.channels.OverlappingFileLockException e) { throw ProtocolException.invalid("Project is being modified by this process; retry after it completes"); } - }); + }); } finally { local.unlock(); } } private static java.nio.channels.FileLock acquire(FileChannel channel, boolean bounded) throws IOException { if (!bounded) return channel.lock(); diff --git a/src/main/java/net/intrepid/aiengineering/filesystem/SqliteDatabase.java b/src/main/java/net/intrepid/aiengineering/filesystem/SqliteDatabase.java index fe36ccb..74828c5 100644 --- a/src/main/java/net/intrepid/aiengineering/filesystem/SqliteDatabase.java +++ b/src/main/java/net/intrepid/aiengineering/filesystem/SqliteDatabase.java @@ -19,6 +19,7 @@ public final class SqliteDatabase { final Connection connection; final boolean write; boolean rollbackOnly; + Boolean selectedBackend; final List committed = new ArrayList<>(); final List rolledBack = new ArrayList<>(); Session(Connection connection, boolean write) { this.connection = connection; this.write = write; } @@ -27,6 +28,18 @@ public final class SqliteDatabase { public static Path path(Path root) { return Filespace.resolve(root, ".ai-engineering/aie.db"); } public static boolean active(Path root) { + // Bootstrap selection is stable for a transaction, not inferred from an open connection or cached across commands. + var sessions=SESSIONS.get(); + // A lookup key only: do not inspect an unused SQLite path in a legacy project. + var session=sessions.get(root.toAbsolutePath().normalize().resolve(".ai-engineering/aie.db")); + if(session==null) { + if(sessions.isEmpty())SESSIONS.remove(); + return selectedByBootstrap(root); + } + if(session.selectedBackend==null)session.selectedBackend=selectedByBootstrap(root); + return session.selectedBackend; + } + private static boolean selectedByBootstrap(Path root) { Path config = Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"); if (!Files.isRegularFile(config, LinkOption.NOFOLLOW_LINKS)) return false; var node = Documents.read(config, tools.jackson.databind.node.ObjectNode.class).get("storage"); diff --git a/src/main/java/net/intrepid/aiengineering/localserver/InvocationClient.java b/src/main/java/net/intrepid/aiengineering/localserver/InvocationClient.java new file mode 100644 index 0000000..a0e1e9d --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/InvocationClient.java @@ -0,0 +1,93 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.*; +import java.util.concurrent.atomic.*; + +/** One submit, event-driven monitoring and bounded recovery. A transport failure never resubmits execution. */ +public final class InvocationClient { + private final BufferedReader input; + private final PrintWriter err; + private final RemoteOutput output; + private final ServerManager manager; + private final ServerProtocol.Request request; + private final AtomicReference endpoint; + private ServerProtocol.Input pendingInput; + private int readSequence,acceptedSequence; + private boolean uncertainInput; + private ServerProtocol.View terminalInput; + public InvocationClient(ServerManager manager,ServerState.Descriptor descriptor,ServerProtocol.Request request, + Reader input,PrintWriter out,PrintWriter err) { + this.manager=manager;this.request=request;this.endpoint=new AtomicReference<>(descriptor); + this.input=new BufferedReader(input);this.err=err;this.output=new RemoteOutput(out,err); + } + private ServerConnection connection(){return new ServerConnection(endpoint.get());} + private boolean terminal(String state){return state.equals("COMPLETED") || state.equals("UNKNOWN");} + private void unknown(String state) { + if(state.equals("UNKNOWN")){err.println("AIE request "+request.id()+" has an unknown outcome; inspect effects before retrying.");err.flush();} + } + private ServerProtocol.View recover() throws IOException { + err.println("Recovering request "+request.id()+" without resubmitting the command.");err.flush(); + endpoint.set(manager.ensure(15000,null)); + try{return connection().call("GET","/requests/"+request.id(),null,ServerProtocol.View.class);} + catch(ProtocolException unavailable){throw ProtocolException.validation("Request "+request.id()+" has no recoverable result; outcome unknown, command was not resent. Inspect effects before retrying");} + } + private void input(ServerProtocol.Event event) throws IOException { + if(!event.needsInput() || event.inputSequence()<=acceptedSequence)return; + if(event.inputSequence()>readSequence) { + String line=input.readLine();readSequence=event.inputSequence(); + pendingInput=new ServerProtocol.Input(request.id(),readSequence,line==null?null:line+"\n"); + } + if(pendingInput==null || pendingInput.sequence()!=event.inputSequence()) + throw ProtocolException.validation("Interactive input sequence changed; inspect request "+request.id()); + uncertainInput=true; + var view=connection().call("POST","/input",pendingInput,ServerProtocol.View.class); + uncertainInput=false;acceptedSequence=pendingInput.sequence(); + if(terminal(view.state()))terminalInput=view; + } + public int run() throws IOException { + var finished=new AtomicBoolean(); + Thread cancellation=new Thread(()->{ + if(!finished.get())try{connection().call("POST","/cancel",new ServerProtocol.Cancel(request.id()),ServerProtocol.View.class);} + catch(IOException | RuntimeException ignored){/* Cancellation cannot assert rollback. */} + },"aie-client-cancel"); + Runtime.getRuntime().addShutdownHook(cancellation); + try { + ServerProtocol.View view; + try{view=connection().call("POST","/execute",request,ServerProtocol.View.class);} + catch(IOException interrupted){view=recover();} + unknown(view.state());output.snapshot(view); + if(terminal(view.state()))return view.exitCode(); + err.println("AIE request "+request.id()+" "+view.state()+" (SSE)");err.flush(); + String cursor=null;int reconnects=0;long progress=System.nanoTime(); + while(true) { + try(var stream=connection().events(request.id(),cursor)) { + while(true) { + var event=stream.next(); + if(event!=null) { + unknown(event.state());output.accept(event);cursor=event.cursor(); + if(event.terminal())return event.exitCode(); + input(event); + if(terminalInput!=null){unknown(terminalInput.state());output.snapshot(terminalInput);return terminalInput.exitCode();} + } + if(System.nanoTime()-progress>=5_000_000_000L){err.println("AIE request "+request.id()+" in progress (SSE)");err.flush();progress=System.nanoTime();} + } + }catch(IOException disconnected) { + if(++reconnects>3)throw ProtocolException.validation("SSE reconnection limit reached for request "+request.id()+"; inspect/recover its outcome. Command was not resent"); + err.println("SSE interrupted; resuming request "+request.id()+" (attempt "+reconnects+"/3)");err.flush(); + try{Thread.sleep(100L<<(reconnects-1));} + catch(InterruptedException interrupted){Thread.currentThread().interrupt();throw ProtocolException.validation("Interrupted recovering request "+request.id());} + var previous=endpoint.get();endpoint.set(manager.ensure(15000,null)); + if(uncertainInput || !previous.instance().equals(endpoint.get().instance())) { + view=recover();uncertainInput=false;unknown(view.state());output.snapshot(view); + if(terminal(view.state()))return view.exitCode(); + cursor=null; + } + } + } + }finally{ + finished.set(true); + try{Runtime.getRuntime().removeShutdownHook(cancellation);}catch(IllegalStateException shuttingDown){/* Hook is already cancelling. */} + } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java b/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java new file mode 100644 index 0000000..ed931a5 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/InvocationPolicy.java @@ -0,0 +1,32 @@ +package net.intrepid.aiengineering.localserver; + +import picocli.CommandLine; +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 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"); + public static String path(CommandLine.ParseResult parse) { + var parts = new ArrayList(); + for (var child = parse.subcommand(); child != null; child = child.subcommand()) + parts.add(child.commandSpec().name()); + return String.join(" ", parts); + } + public static boolean local(CommandLine.ParseResult parse) { + if (path(parse).isEmpty() || LOCAL.contains(path(parse))) return true; + for (var current = parse; current != null; current = current.subcommand()) + if (current.isUsageHelpRequested() || current.isVersionHelpRequested()) return true; + return false; + } + public static boolean readOnly(CommandLine.ParseResult parse) { + return READS.contains(path(parse)); // Unknown/new commands conservatively count as mutations. + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/JobEvents.java b/src/main/java/net/intrepid/aiengineering/localserver/JobEvents.java new file mode 100644 index 0000000..a536b4d --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/JobEvents.java @@ -0,0 +1,69 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.util.*; +import java.util.function.Supplier; + +/** Bounded replay under the job monitor. Network I/O belongs to the subscriber after next returns. */ +public final class JobEvents implements ServerProtocol.EventSource { + public static final int MAX_EVENTS = 128, MAX_REPLAY_CHARS = 256 * 1024, CHUNK_CHARS = 16 * 1024; + private final Object monitor; + private final Supplier snapshot; + private final String generation = UUID.randomUUID().toString(); + private final ArrayDeque history = new ArrayDeque<>(); + private long sequence; + private int characters; + private boolean terminal; + public JobEvents(Object monitor, Supplier snapshot) { + this.monitor=monitor; this.snapshot=snapshot; + } + public static void validateCursor(String cursor) { + if (cursor == null) return; + if (!cursor.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}:[0-9]{1,19}")) + throw ProtocolException.invalid("Invalid SSE event cursor"); + try { if (Long.parseLong(cursor.substring(37)) < 0) throw new NumberFormatException(); } + catch (NumberFormatException invalid) { throw ProtocolException.invalid("Invalid SSE event cursor"); } + } + private ServerProtocol.Event event(String kind, int outOffset, int errOffset, String out, String err, ServerProtocol.View view) { + return new ServerProtocol.Event(view.id(),generation+":"+sequence,kind,outOffset,errOffset,out,err, + view.state(),view.exitCode(),view.inputSequence(),view.needsInput(),view.cancellationRequested()); + } + public void publish(String kind, int outOffset, int errOffset, String out, String err, ServerProtocol.View metadata) { + synchronized (monitor) { + sequence++; + var event=event(kind,outOffset,errOffset,out,err,metadata); + history.addLast(event); characters+=out.length()+err.length(); terminal=event.terminal(); + while (history.size()>MAX_EVENTS || characters>MAX_REPLAY_CHARS) { + var removed=history.removeFirst(); characters-=removed.stdout().length()+removed.stderr().length(); + } + monitor.notifyAll(); + } + } + private ServerProtocol.Event snapshotEvent() { + var view=snapshot.get(); + return event("snapshot",0,0,view.stdout(),view.stderr(),view); + } + @Override public ServerProtocol.Event next(String cursor, long timeoutMillis) throws InterruptedException { + validateCursor(cursor); + long deadline=System.nanoTime()+Math.max(0,timeoutMillis)*1_000_000; + synchronized (monitor) { + while (true) { + if (cursor==null || !cursor.startsWith(generation+":")) return snapshotEvent(); + long after=Long.parseLong(cursor.substring(37)); + long oldest=sequence-history.size()+1; + if (after>sequence || afterafter) return event; + if (terminal) return snapshotEvent(); + long remaining=deadline-System.nanoTime(); + if (remaining<=0) return null; + java.util.concurrent.TimeUnit.NANOSECONDS.timedWait(monitor,remaining); + } + } + } + public static ServerProtocol.EventSource completed(ServerProtocol.View view) { + if (!Set.of("COMPLETED","UNKNOWN").contains(view.state())) + throw ProtocolException.validation("Live request has no event source"); + var events=new JobEvents(new Object(),()->view); + return (cursor,timeout)->{ validateCursor(cursor); return events.snapshotEvent(); }; + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/LocalClient.java b/src/main/java/net/intrepid/aiengineering/localserver/LocalClient.java new file mode 100644 index 0000000..8c468f6 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/LocalClient.java @@ -0,0 +1,92 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.cli.EngineeringCli; +import net.intrepid.aiengineering.filesystem.ProtocolException; +import picocli.CommandLine; +import picocli.CommandLine.*; +import java.io.*; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.Callable; + +/** The public client path never opens a Spring context. */ +public final class LocalClient { + private final Path cwd; + private final Reader input; + private final PrintWriter out, err; + private final boolean interactive; + public LocalClient(Path cwd, Reader input, PrintWriter out, PrintWriter err, boolean interactive) { + this.cwd = cwd.toAbsolutePath().normalize(); this.input = input; this.out = out; this.err = err; this.interactive = interactive; + } + public int execute(String... args) { + var cli = new EngineeringCli(cwd, input, interactive); + var parser = cli.commandLineFor(out, err, args); + parser.addSubcommand("start", new Start(cli)); parser.addSubcommand("stop", new Stop(cli)); + parser.addSubcommand("server", new Management(cli)); + configure(parser); + try { + var parsed = parser.parseArgs(args); + String path = InvocationPolicy.path(parsed); + if (InvocationPolicy.local(parsed) || path.equals("start") || path.equals("stop") || path.startsWith("server")) + return parser.execute(args); + Path root = cli.selectedRoot(); + var manager = new ServerManager(root); + var descriptor = manager.ensure(15000, null); + return forward(manager, descriptor, new ServerProtocol.Request(UUID.randomUUID().toString(), + root.toString(), cwd.toString(), List.of(args), interactive)); + } catch (ParameterException failure) { return parser.execute(args); } + catch (ProtocolException failure) { err.println(failure.getMessage()); return failure.exitCode(); } + catch (Exception failure) { err.println("Local AIE client failed: " + failure.getMessage()); return 1; } + finally { out.flush(); err.flush(); } + } + private void configure(CommandLine parser) { + parser.setOut(out).setErr(err); + parser.getSubcommands().values().forEach(this::configure); + } + private int forward(ServerManager manager, ServerState.Descriptor descriptor, ServerProtocol.Request request) throws IOException { + return new InvocationClient(manager,descriptor,request,input,out,err).run(); + } + private ServerManager manager(EngineeringCli cli) { return new ServerManager(cli.selectedRoot()); } + @Command(name="start", mixinStandardHelpOptions=true, description="Start or reuse this project's local server; wait for readiness.") + public final class Start implements Callable { + final EngineeringCli cli; + @Option(names="--idle-timeout-seconds", description="Stop after this many idle seconds; default 1800. Active operations are preserved.") Long idle; + @Option(names="--timeout-seconds", defaultValue="15") int timeout; + Start(EngineeringCli cli) { this.cli=cli; } + public Integer call() { + var descriptor = manager(cli).ensure(seconds(timeout), idle == null ? null : seconds(idle)); + out.println("AIE server ready: project=" + descriptor.root() + " pid=" + descriptor.pid() + " port=" + descriptor.port()); return 0; + } + } + @Command(name="stop", mixinStandardHelpOptions=true, description="Drain and stop this project's server; already stopped is success.") + public final class Stop implements Callable { + final EngineeringCli cli; + @Option(names="--timeout-seconds", defaultValue="30") int timeout; + Stop(EngineeringCli cli) { this.cli=cli; } + public Integer call() { manager(cli).stop(seconds(timeout)); out.println("AIE server stopped."); return 0; } + } + @Command(name="server", mixinStandardHelpOptions=true, description="Inspect the local server and recover or cancel request IDs.") + public final class Management { + final EngineeringCli cli; + Management(EngineeringCli cli) { this.cli=cli; } + @Command(name="status", mixinStandardHelpOptions=true) + int status() { out.println(ServerJson.encode(manager(cli).status())); return 0; } + @Command(name="request", mixinStandardHelpOptions=true) + int request(@Parameters(index="0") String id) throws IOException { + ServerProtocol.identifier(id); + var endpoint=manager(cli).ensure(15000,null); + out.println(ServerJson.encode(new ServerConnection(endpoint).call("GET","/requests/"+id,null,ServerProtocol.View.class))); return 0; + } + @Command(name="cancel", mixinStandardHelpOptions=true) + int cancel(@Parameters(index="0") String id) throws IOException { + ServerProtocol.identifier(id); + var state=manager(cli).state(); var endpoint=state.descriptor(); + if (endpoint==null || !state.owned()) throw ProtocolException.missing("No running project server; inspect the request outcome before retrying"); + out.println(ServerJson.encode(new ServerConnection(endpoint).call("POST","/cancel",new ServerProtocol.Cancel(id),ServerProtocol.View.class))); return 0; + } + } + private static long seconds(long value) { + if (value < 1 || value > 604800) throw ProtocolException.invalid("Timeout must be between 1 and 604800 seconds"); + return value * 1000; + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ProjectServer.java b/src/main/java/net/intrepid/aiengineering/localserver/ProjectServer.java new file mode 100644 index 0000000..7bf1ed2 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ProjectServer.java @@ -0,0 +1,150 @@ +package net.intrepid.aiengineering.localserver; + +import com.sun.net.httpserver.*; +import net.intrepid.aiengineering.filesystem.*; +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; + +/** One authenticated loopback listener per canonical project, independent of HTTP sessions. */ +public final class ProjectServer implements AutoCloseable { + private final ServerState state; + private final ServerState.Lease owner; + private final ServerProtocol.Operations operations; + private final SseStreams streams; + private final HttpServer http; + private final ExecutorService connections = new ThreadPoolExecutor(2, 8, 30, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(64), Thread.ofPlatform().daemon().name("aie-http-", 0).factory()); + private final ScheduledExecutorService lifecycle = Executors.newSingleThreadScheduledExecutor( + Thread.ofPlatform().daemon().name("aie-lifecycle").factory()); + private final CountDownLatch terminated = new CountDownLatch(1); + private final AtomicBoolean closed = new AtomicBoolean(); + private final Object admission = new Object(); + private final ServerState.Descriptor descriptor; + private final long idleMillis; + private volatile boolean draining; + private volatile long lastActive = System.nanoTime(); + + public ProjectServer(ServerState state, long idleMillis, ServerProtocol.Operations operations) { + if (idleMillis < 1) throw ProtocolException.invalid("Idle timeout must be positive"); + this.state = state; this.idleMillis = idleMillis; this.operations = operations; + owner = state.lock("owner.lock", 0); + if (owner == null) throw ProtocolException.validation("A project server already owns this project"); + streams=new SseStreams(); + HttpServer listener = null; + try { + listener = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 32); + http = listener; + byte[] token = new byte[32]; new SecureRandom().nextBytes(token); + descriptor = new ServerState.Descriptor(ServerIdentity.PROTOCOL, ServerIdentity.BUILD, + state.root.toString(), UUID.randomUUID().toString(), ProcessHandle.current().pid(), + http.getAddress().getPort(), HexFormat.of().formatHex(token)); + http.setExecutor(connections); http.createContext("/", this::handle); + http.start(); + state.publish(descriptor); // Published only after command infrastructure and listener are ready. + lifecycle.scheduleWithFixedDelay(this::tick, 100, 100, TimeUnit.MILLISECONDS); + } catch (IOException | RuntimeException failure) { + if (listener != null) listener.stop(0); + connections.shutdownNow(); lifecycle.shutdownNow(); streams.close(); owner.close(); + throw failure instanceof RuntimeException runtime ? runtime : new ProtocolException(1, "Cannot start loopback server: " + failure.getMessage()); + } + } + public ServerState.Descriptor descriptor() { return descriptor; } + public int eventSubscribers() { return streams.active(); } + public ServerProtocol.Health health() { + return new ServerProtocol.Health(descriptor.protocol(), descriptor.build(), descriptor.root(), + descriptor.instance(), descriptor.pid(), draining, operations.active(), idleMillis, operations.pending()); + } + public void await() throws InterruptedException { terminated.await(); } + public boolean await(long milliseconds) throws InterruptedException { return terminated.await(milliseconds, TimeUnit.MILLISECONDS); } + public void drain() { synchronized (admission) { draining = true; } } + private void tick() { + try { + synchronized (admission) { + if (operations.active() > 0) { lastActive = System.nanoTime(); return; } + if (!draining && (System.nanoTime() - lastActive) / 1_000_000 < idleMillis) return; + draining = true; + } + if(!streams.drained()) return; + close(); + } catch (RuntimeException failure) { System.err.println("AIE server lifecycle failed: " + failure.getMessage()); } + } + private void handle(HttpExchange exchange) throws IOException { + boolean delegated=false; + try { + try { + String authorization = exchange.getRequestHeaders().getFirst("Authorization"); + String expected = "Bearer " + descriptor.token(); + if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress() || authorization == null + || !MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), authorization.getBytes(StandardCharsets.UTF_8))) { + reply(exchange, 403, new ServerProtocol.Error(4, "Local server authentication failed")); return; + } + if (exchange.getRequestHeaders().containsKey("Origin")) { + reply(exchange, 403, new ServerProtocol.Error(4, "Browser-origin requests are not supported")); return; + } + if (!descriptor.instance().equals(exchange.getRequestHeaders().getFirst("X-AIE-Instance"))) { + reply(exchange, 409, new ServerProtocol.Error(4, "Server instance changed; rediscover the endpoint")); return; + } + String path = exchange.getRequestURI().getPath(), method = exchange.getRequestMethod(); + if (path.equals("/health") && method.equals("GET")) { reply(exchange, 200, health()); return; } + if (!Integer.toString(ServerIdentity.PROTOCOL).equals(exchange.getRequestHeaders().getFirst("X-AIE-Protocol"))) { + reply(exchange, 409, new ServerProtocol.Error(4, "Incompatible server protocol")); return; + } + if (path.equals("/stop") && method.equals("POST")) { drain(); reply(exchange, 200, health()); return; } + if (path.equals("/execute") && method.equals("POST")) { + var request = body(exchange, ServerProtocol.Request.class); + ServerProtocol.View result; + synchronized (admission) { + if (draining) { reply(exchange, 503, new ServerProtocol.Error(4, "Server is draining; no command was admitted")); return; } + if (!descriptor.root().equals(request.project())) throw ProtocolException.invalid("Request belongs to another project"); + lastActive = System.nanoTime(); + result=operations.submit(request); + } + reply(exchange,200,result); + return; + } + if(path.startsWith("/requests/") && path.endsWith("/events") && method.equals("GET")) { + String id=ServerProtocol.identifier(path.substring("/requests/".length(),path.length()-"/events".length())); + String cursor=exchange.getRequestHeaders().getFirst("Last-Event-ID"); + JobEvents.validateCursor(cursor); + streams.open(exchange,id,cursor,operations.events(id)); delegated=true; return; + } + if (path.startsWith("/requests/") && method.equals("GET")) { + reply(exchange, 200, operations.get(ServerProtocol.identifier(path.substring("/requests/".length())))); return; + } + if (path.equals("/input") && method.equals("POST")) { reply(exchange, 200, operations.input(body(exchange, ServerProtocol.Input.class))); return; } + if (path.equals("/cancel") && method.equals("POST")) { reply(exchange, 200, operations.cancel(body(exchange, ServerProtocol.Cancel.class).id())); return; } + reply(exchange, 404, new ServerProtocol.Error(3, "Unknown local-server operation")); + } catch (ProtocolException failure) { + reply(exchange, failure.exitCode() == 3 ? 404 : 400, new ServerProtocol.Error(failure.exitCode(), failure.getMessage())); + } catch (RuntimeException failure) { + reply(exchange, 500, new ServerProtocol.Error(1, "Local server operation failed")); + } + } finally { if(!delegated) exchange.close(); } + } + private T body(HttpExchange exchange, Class type) throws IOException { + if (!"application/json".equals(exchange.getRequestHeaders().getFirst("Content-Type"))) + throw ProtocolException.invalid("Expected application/json"); + byte[] bytes = exchange.getRequestBody().readNBytes(1024 * 1024 + 1); + if (bytes.length > 1024 * 1024) throw ProtocolException.invalid("Local request exceeds 1 MiB"); + return ServerJson.decode(new String(bytes, StandardCharsets.UTF_8), type); + } + private static void reply(HttpExchange exchange, int code, Object value) throws IOException { + byte[] bytes = ServerJson.encode(value).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.getResponseHeaders().set("Cache-Control", "no-store"); + exchange.sendResponseHeaders(code, bytes.length); + exchange.getResponseBody().write(bytes); + } + @Override public void close() { + if (!closed.compareAndSet(false, true)) return; + drain(); + try { streams.close(); http.stop(0); operations.close(); state.removeDescriptor(descriptor.instance()); } + finally { connections.shutdownNow(); lifecycle.shutdown(); owner.close(); terminated.countDown(); } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/RemoteOutput.java b/src/main/java/net/intrepid/aiengineering/localserver/RemoteOutput.java new file mode 100644 index 0000000..cabfe95 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/RemoteOutput.java @@ -0,0 +1,27 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.PrintWriter; + +/** Verify overlaps before printing; snapshots and resumed deltas cannot silently repeat or replace output. */ +public final class RemoteOutput { + private final StringBuilder stdout=new StringBuilder(),stderr=new StringBuilder(); + private final PrintWriter out,err; + public RemoteOutput(PrintWriter out,PrintWriter err){this.out=out;this.err=err;} + private void append(StringBuilder previous,PrintWriter writer,int offset,String text,boolean snapshot) { + if(offset<0 || offset>previous.length() || (snapshot && (offset!=0 || text.length() jobs = new ConcurrentHashMap<>(); + private final Queue completed = new ConcurrentLinkedQueue<>(); + private final AtomicInteger active = new AtomicInteger(); + private final ExecutorService commands = new ThreadPoolExecutor(4, 4, 30, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(64), Thread.ofPlatform().daemon().name("aie-command-", 0).factory()); + private final ExecutorService longCommands = new ThreadPoolExecutor(0, 4, 30, TimeUnit.SECONDS, + new SynchronousQueue<>(), Thread.ofPlatform().daemon().name("aie-job-", 0).factory()); + public RequestJobs(ServerState files) { + this(files, (request, input, out, err) -> new EngineeringCli(Path.of(request.cwd()), input, request.interactive()) + .execute(out, err, request.argv().toArray(String[]::new))); + } + public RequestJobs(ServerState files, Runner runner) { + this.files = files; this.runner = runner; files.initialize(); + Filespace.directory(files.file("requests")); ServerState.permissions(files.file("requests"), "rwx------"); + } + private Path receipt(String id) { return files.file("requests/" + ServerProtocol.identifier(id) + ".json"); } + private Receipt stored(String id) { + Path path = receipt(id); + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return null; + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Filespace.io(() -> Files.size(path)) > 128 * 1024 * 1024) + throw ProtocolException.validation("Invalid local request receipt"); + var value = ServerJson.decode(Filespace.read(path), Receipt.class); + if (!id.equals(value.id()) || value.fingerprint() == null || !value.fingerprint().matches("[a-f0-9]{64}") + || value.stdout() == null || value.stderr() == null || value.state() == null + || !Set.of("QUEUED", "RUNNING", "COMPLETED", "UNKNOWN").contains(value.state()) + || (value.state().equals("COMPLETED") && value.exitCode() < 0)) + throw ProtocolException.validation("Invalid local request receipt identity"); + return value; + } + private ServerProtocol.View view(Receipt value) { + boolean complete = value.state().equals("COMPLETED"); + return new ServerProtocol.View(value.id(), complete ? "COMPLETED" : "UNKNOWN", complete ? value.exitCode() : 4, + value.stdout(), value.stderr() + (complete ? "" : "\nRequest outcome unknown after server interruption; inspect effects before submitting another mutation.\n"), + 0, false, value.cancellationRequested()); + } + @Override public ServerProtocol.View submit(ServerProtocol.Request request) { + Job selected; + synchronized (this) { + selected = jobs.get(request.id()); + if (selected != null) { + if (!selected.request.fingerprint().equals(request.fingerprint())) throw ProtocolException.invalid("Request ID already used for different input"); + } else { + var previous = stored(request.id()); + if (previous != null) { + if (!previous.fingerprint().equals(request.fingerprint())) throw ProtocolException.invalid("Request ID already used for different input"); + return view(previous); // Never replay an interrupted mutation. + } + if (active.get() >= 68) throw ProtocolException.validation("Project command queue is full; no command was admitted"); + Path cwd = Filespace.io(() -> Path.of(request.cwd()).toRealPath()); + var cli = new EngineeringCli(cwd, Reader.nullReader(), request.interactive()); + boolean readOnly = false, longRunning = false; + try { + var parsed = cli.commandLineFor(new PrintWriter(Writer.nullWriter()), new PrintWriter(Writer.nullWriter()), request.argv().toArray(String[]::new)) + .parseArgs(request.argv().toArray(String[]::new)); + if (InvocationPolicy.local(parsed)) throw ProtocolException.invalid("Bootstrap commands execute in the local client"); + if (!cli.selectedRoot().equals(files.root) || !request.project().equals(files.root.toString())) + throw ProtocolException.invalid("Request belongs to another project"); + readOnly = InvocationPolicy.readOnly(parsed); + longRunning = Set.of("agent run", "survey ask").contains(InvocationPolicy.path(parsed)); + } catch (CommandLine.ParameterException invalid) { + // The normal CLI will render the original parse diagnostic and return its exit code. + } + selected = new Job(request, !readOnly); + if (selected.durable) selected.persist("QUEUED", -1); + jobs.put(request.id(), selected); active.incrementAndGet(); + try { (longRunning ? longCommands : commands).execute(selected); } + catch (RejectedExecutionException full) { selected.failAdmission(); } + } + } + return selected.awaitView(60); + } + @Override public ServerProtocol.View get(String id) { + ServerProtocol.identifier(id); + var job = jobs.get(id); + if (job != null) return job.awaitView(100); + var receipt = stored(id); + if (receipt == null) throw ProtocolException.missing("Local request not found: " + id); + return view(receipt); + } + @Override public ServerProtocol.EventSource events(String id) { + ServerProtocol.identifier(id); + var job=jobs.get(id); + if (job!=null) return job.events; + var receipt=stored(id); + if (receipt==null) throw ProtocolException.missing("Local request not found: "+id); + return JobEvents.completed(view(receipt)); + } + @Override public ServerProtocol.View input(ServerProtocol.Input input) { + var job = jobs.get(input.id()); + if (job == null) throw ProtocolException.missing("Active input request not found"); + synchronized (job) { + if (input.sequence() == job.acceptedInput) return job.snapshot(); + if (!job.needsInput || input.sequence() != job.inputSequence) throw ProtocolException.invalid("Stale input sequence"); + if (input.text() != null && input.text().length() > MAX_CHARS) throw ProtocolException.invalid("Input exceeds local limit"); + job.acceptedInput = input.sequence(); job.needsInput = false; + if (input.text() == null) job.eof = true; + else job.pendingInput.append(input.text()); + job.publishStatus(); return job.snapshot(); + } + } + @Override public ServerProtocol.View cancel(String id) { + var job = jobs.get(ServerProtocol.identifier(id)); + if (job == null) return get(id); + synchronized (job) { + if (!job.terminal()) { + job.cancellation = true; + if (job.thread != null) job.thread.interrupt(); + job.publishStatus(); + } + return job.snapshot(); + } + } + @Override public int active() { return active.get(); } + @Override public List pending() { + return jobs.values().stream().filter(job -> !job.terminal()).map(job -> job.request.id()).sorted().toList(); + } + @Override public void close() { + commands.shutdown(); longCommands.shutdown(); + if (active.get() > 0) jobs.values().forEach(job -> cancel(job.request.id())); + } + private final class Job implements Runnable { + final ServerProtocol.Request request; + final boolean durable; + final StringBuilder stdout = new StringBuilder(), stderr = new StringBuilder(), pendingInput = new StringBuilder(); + String state = "QUEUED"; + int exit = -1, inputSequence, acceptedInput; + boolean cancellation, needsInput, eof; + Thread thread; + final JobEvents events; + Job(ServerProtocol.Request request, boolean durable) { + this.request = request; this.durable = durable; events=new JobEvents(this,this::snapshot); + } + void publishStatus() { + String kind=state.equals("COMPLETED")?"completed":state.equals("UNKNOWN")?"unknown":needsInput?"input-required":"progress"; + events.publish(kind,stdout.length(),stderr.length(),"","",metadata()); + } + ServerProtocol.View metadata() { + return new ServerProtocol.View(request.id(),state,exit,"","",inputSequence,needsInput,cancellation); + } + void append(StringBuilder target, char[] value, int offset, int length) { + while (length>0) { + int count=Math.min(length,JobEvents.CHUNK_CHARS); + int outOffset=stdout.length(),errOffset=stderr.length(); + String text=new String(value,offset,count); target.append(text); + events.publish(target==stdout?"stdout":"stderr",outOffset,errOffset, + target==stdout?text:"",target==stderr?text:"",metadata()); + offset+=count; length-=count; + } + } + void error(String text) { + char[] chars=text.toCharArray(); append(stderr,chars,0,chars.length); + } + synchronized boolean terminal() { return state.equals("COMPLETED") || state.equals("UNKNOWN"); } + synchronized ServerProtocol.View snapshot() { + return new ServerProtocol.View(request.id(), state, exit, stdout.toString(), stderr.toString(), inputSequence, needsInput, cancellation); + } + synchronized ServerProtocol.View awaitView(long millis) { + long deadline = System.nanoTime() + millis * 1_000_000; + while (!terminal() && !needsInput && System.nanoTime() < deadline) { + try { TimeUnit.NANOSECONDS.timedWait(this, Math.max(1, deadline - System.nanoTime())); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); break; } + } + return snapshot(); + } + synchronized void persist(String state, int exit) { + ServerState.write(receipt(request.id()), ServerJson.encode(new Receipt(request.id(), request.fingerprint(), state, + exit, stdout.toString(), stderr.toString(), cancellation))); + } + PrintWriter writer(StringBuilder target) { + return new PrintWriter(new Writer() { + public void write(char[] value, int offset, int length) { + synchronized (Job.this) { + if (target.length() + length > MAX_CHARS) throw ProtocolException.validation("Command output exceeds 8 MiB characters per stream"); + Job.this.append(target,value,offset,length); + } + } + public void flush() {} + public void close() {} + }, true); + } + Reader reader() { + return new Reader() { + public int read(char[] value, int offset, int length) throws IOException { + if (length == 0) return 0; + synchronized (Job.this) { + while (pendingInput.isEmpty() && !eof) { + if (!request.interactive()) return -1; + if (cancellation) throw new IOException("Input cancelled; prior effects may exist"); + if (!needsInput) { needsInput = true; inputSequence++; publishStatus(); } + try { Job.this.wait(); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Input interrupted; prior effects may exist"); } + } + if (pendingInput.isEmpty()) return -1; + int count = Math.min(length, pendingInput.length()); + pendingInput.getChars(0, count, value, offset); pendingInput.delete(0, count); return count; + } + } + public void close() {} + }; + } + @Override public void run() { + synchronized (this) { state = "RUNNING"; thread = Thread.currentThread(); publishStatus(); } + int result; + try { + synchronized (this) { if (cancellation) throw ProtocolException.validation("Command cancelled before execution"); } + result = runner.run(request, reader(), writer(stdout), writer(stderr)); + } catch (Exception failure) { + result = failure instanceof ProtocolException protocol ? protocol.exitCode() : 1; + synchronized (this) { + String message=failure.getMessage()==null?"Command failed":failure.getMessage(); + error("\n"+message.substring(0,Math.min(message.length(),1024))+"\n"); + } + } finally { Thread.interrupted(); /* Receipt publication must not inherit a cancelled channel's interrupt. */ } + finish(result); + } + void failAdmission() { synchronized (this) { error("Project worker capacity exceeded; command was not executed.\n"); } finish(4); } + void finish(int result) { + synchronized (this) { + // Persist read results too: evicting the bounded RAM cache must not lose a client's result. + try { persist("COMPLETED", result); state = "COMPLETED"; exit = result; } + catch (RuntimeException failure) { error("\nCannot publish command outcome; inspect effects before retry.\n"); state = "UNKNOWN"; exit = 4; } + thread = null; needsInput = false; publishStatus(); + } + active.decrementAndGet(); + if (state.equals("COMPLETED")) { jobs.remove(request.id(), this); return; } + completed.add(request.id()); + while (completed.size() > 64) { String id = completed.poll(); if (id != null) jobs.remove(id); } + } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerConnection.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerConnection.java new file mode 100644 index 0000000..51007f1 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerConnection.java @@ -0,0 +1,75 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; + +/** Direct loopback transport: no proxy, redirects, Spring context or shell. */ +public final class ServerConnection { + private final ServerState.Descriptor descriptor; + public ServerConnection(ServerState.Descriptor descriptor) { this.descriptor = descriptor; } + private HttpURLConnection open(String method,String path) throws IOException { + var connection = (HttpURLConnection) URI.create("http://127.0.0.1:" + descriptor.port() + path) + .toURL().openConnection(Proxy.NO_PROXY); + connection.setConnectTimeout(1000); connection.setReadTimeout(5000); + connection.setInstanceFollowRedirects(false); connection.setRequestMethod(method); + connection.setRequestProperty("Authorization", "Bearer " + descriptor.token()); + connection.setRequestProperty("X-AIE-Instance", descriptor.instance()); + connection.setRequestProperty("X-AIE-Protocol", Integer.toString(ServerIdentity.PROTOCOL)); + return connection; + } + public T call(String method, String path, Object body, Class type) throws IOException { + var connection=open(method,path); + if (body != null) { + byte[] bytes = ServerJson.encode(body).getBytes(StandardCharsets.UTF_8); + connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); + connection.setFixedLengthStreamingMode(bytes.length); + try (var output = connection.getOutputStream()) { output.write(bytes); } + } + int status = connection.getResponseCode(); + InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream(); + if (stream == null) throw new IOException("Local server returned HTTP " + status); + String text; + try (stream) { + byte[] bytes = stream.readNBytes(128 * 1024 * 1024 + 1); + if (bytes.length > 128 * 1024 * 1024) throw new IOException("Local server response exceeds 128 MiB"); + text = new String(bytes, StandardCharsets.UTF_8); + } + if (status != 200) { + var error = ServerJson.decode(text, ServerProtocol.Error.class); + throw new ProtocolException(error.exitCode(), error.message()); + } + return ServerJson.decode(text, type); + } + public EventStream events(String id,String cursor) throws IOException { + ServerProtocol.identifier(id);JobEvents.validateCursor(cursor); + var connection=open("GET","/requests/"+id+"/events"); + connection.setRequestProperty("Accept","text/event-stream"); + if(cursor!=null)connection.setRequestProperty("Last-Event-ID",cursor); + try { + int status=connection.getResponseCode(); + if(status!=200) { + var stream=connection.getErrorStream(); + if(stream==null)throw new IOException("SSE returned HTTP "+status); + try(stream) { + var error=ServerJson.decode(new String(stream.readNBytes(16384),StandardCharsets.UTF_8),ServerProtocol.Error.class); + throw new ProtocolException(error.exitCode(),error.message()); + } + } + String content=connection.getContentType(); + if(content==null || !content.split(";",2)[0].equalsIgnoreCase("text/event-stream")) + throw ProtocolException.validation("Expected an SSE event stream for "+id); + var decoder=StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT); + return new EventStream(connection,new SseReader(new InputStreamReader(connection.getInputStream(),decoder),id)); + }catch(IOException | RuntimeException failure){connection.disconnect();throw failure;} + } + public static final class EventStream implements AutoCloseable { + private final HttpURLConnection connection; + private final SseReader reader; + private EventStream(HttpURLConnection connection,SseReader reader){this.connection=connection;this.reader=reader;} + public ServerProtocol.Event next() throws IOException{return reader.next();} + @Override public void close(){connection.disconnect();try{reader.close();}catch(IOException alreadyClosed){/* Socket is detached. */}} + } + public ServerProtocol.Health health() throws IOException { return call("GET", "/health", null, ServerProtocol.Health.class); } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerIdentity.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerIdentity.java new file mode 100644 index 0000000..670263a --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerIdentity.java @@ -0,0 +1,21 @@ +package net.intrepid.aiengineering.localserver; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; + +public final class ServerIdentity { + public static final int PROTOCOL = 1; + public static final String BUILD = build(); + private ServerIdentity() {} + public static String hash(String value) { + try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); } + catch (java.security.NoSuchAlgorithmException failure) { throw new IllegalStateException(failure); } + } + private static String build() { + try (var input = ServerIdentity.class.getResourceAsStream("/aie-build.txt")) { + return input == null ? hash("development-unpackaged") : new String(input.readAllBytes(), StandardCharsets.UTF_8).strip(); + } catch (IOException failure) { throw new IllegalStateException("Cannot read server build identity", failure); } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerJson.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerJson.java new file mode 100644 index 0000000..535573d --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerJson.java @@ -0,0 +1,20 @@ +package net.intrepid.aiengineering.localserver; + +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.core.StreamReadFeature; +import net.intrepid.aiengineering.filesystem.ProtocolException; + +/** Transport-only JSON: the lightweight path must not initialize the YAML/domain codecs. */ +public final class ServerJson { + private static final JsonMapper JSON = JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_TRAILING_TOKENS, + DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).build(); + private ServerJson() {} + public static String encode(Object value) { return JSON.writeValueAsString(value); } + public static T decode(String text, Class type) { + try { return JSON.readValue(text, type); } + catch (RuntimeException failure) { throw ProtocolException.invalid("Invalid local-server " + type.getSimpleName()); } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerLaunch.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerLaunch.java new file mode 100644 index 0000000..0716e17 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerLaunch.java @@ -0,0 +1,30 @@ +package net.intrepid.aiengineering.localserver; + +import java.nio.file.*; +import java.util.*; +import net.intrepid.aiengineering.filesystem.ProtocolException; + +/** Re-executes this installed package, never a shell or project-supplied executable. */ +public final class ServerLaunch { + public static final String INTERNAL = "--aie-internal-server"; + private ServerLaunch() {} + public static List current() { + var info = ProcessHandle.current().info(); + String executable = info.command().orElseThrow(() -> ProtocolException.invalid("Cannot locate AIE executable")); + if (System.getProperty("org.graalvm.nativeimage.imagecode") != null) return List.of(executable); + var arguments = List.of(info.arguments().orElse(new String[0])); + int jar = arguments.indexOf("-jar"); + if (jar >= 0 && jar + 1 < arguments.size()) return jar(Path.of(arguments.get(jar + 1))); + return List.of(executable, "--enable-native-access=ALL-UNNAMED", "-cp", absoluteClasspath(), + "net.intrepid.aiengineering.AieLauncher"); + } + public static List jar(Path jar) { + return List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "--enable-native-access=ALL-UNNAMED", "-jar", jar.toAbsolutePath().normalize().toString()); + } + private static String absoluteClasspath() { + return Arrays.stream(System.getProperty("java.class.path").split(java.io.File.pathSeparator)) + .map(value -> Path.of(value).toAbsolutePath().normalize().toString()) + .collect(java.util.stream.Collectors.joining(java.io.File.pathSeparator)); + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerManager.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerManager.java new file mode 100644 index 0000000..71df8d9 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerManager.java @@ -0,0 +1,107 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.*; +import java.io.*; +import java.nio.file.*; +import java.util.*; + +/** Coordinates startup/replacement without killing processes or trusting PIDs as ownership. */ +public final class ServerManager { + public static final long DEFAULT_IDLE_MILLIS = 30 * 60 * 1000L; + public record Status(String state, ServerProtocol.Health server) {} + private final ServerState state; + private final List launcher; + public ServerManager(Path root) { this(root, ServerLaunch.current()); } + public ServerManager(Path root, List launcher) { state = new ServerState(root); this.launcher = List.copyOf(launcher); } + public ServerState state() { return state; } + public Status status() { + var descriptor = state.descriptor(); + if (descriptor == null) return new Status(Files.exists(state.directory) && state.owned() ? "STARTING" : "STOPPED", null); + if (!state.owned()) return new Status("STOPPED", null); + try { return new Status("RUNNING", health(descriptor)); } + catch (IOException unavailable) { return new Status("UNREACHABLE", null); } + } + private ServerProtocol.Health health(ServerState.Descriptor descriptor) throws IOException { + var health = new ServerConnection(descriptor).health(); + if (!health.project().equals(state.root.toString()) || !health.instance().equals(descriptor.instance()) + || health.pid() != descriptor.pid() || !health.build().equals(descriptor.build()) || health.protocol() != descriptor.protocol()) + throw ProtocolException.validation("Local server identity does not match its descriptor"); + return health; + } + public ServerState.Descriptor ensure(long timeoutMillis, Long requestedIdleMillis) { + if (timeoutMillis < 1 || (requestedIdleMillis != null && requestedIdleMillis < 1)) throw ProtocolException.invalid("Server timeouts must be positive"); + long deadline = System.nanoTime() + timeoutMillis * 1_000_000; + try (var start = state.lock("startup.lock", timeoutMillis)) { + if (start == null) throw ProtocolException.validation("Timed out waiting for project server startup lock; no command sent"); + var descriptor = state.descriptor(); + if (descriptor != null && state.owned()) { + try { + var health = health(descriptor); + if (descriptor.compatible() && !health.draining() + && (requestedIdleMillis == null || health.idleMillis() == requestedIdleMillis)) return descriptor; + if (descriptor.protocol() != ServerIdentity.PROTOCOL) + throw ProtocolException.validation("Incompatible server protocol; stop it with its matching AIE version"); + new ServerConnection(descriptor).call("POST", "/stop", null, ServerProtocol.Health.class); + } catch (IOException unavailable) { + throw ProtocolException.validation("Project server owns its lock but is unreachable; inspect " + state.file("startup.log")); + } + waitUnowned(deadline); + } else if (state.owned()) { + // A manually started process may own the lock before it publishes readiness. + return waitReady(deadline, null); + } + descriptor = state.descriptor(); + if (descriptor != null) state.removeDescriptor(descriptor.instance()); + long idle = requestedIdleMillis == null ? DEFAULT_IDLE_MILLIS : requestedIdleMillis; + var command = new ArrayList<>(launcher); + command.addAll(List.of(ServerLaunch.INTERNAL, state.root.toString(), Long.toString(idle))); + Path log = state.file("startup.log"); + ServerState.write(log, ""); + final Process process; + try { + process = new ProcessBuilder(command).directory(state.root.toFile()) + .redirectOutput(log.toFile()).redirectErrorStream(true).start(); + process.getOutputStream().close(); + } catch (IOException failure) { throw new ProtocolException(1, "Cannot launch project server: " + failure.getMessage()); } + return waitReady(deadline, process); + } + } + private ServerState.Descriptor waitReady(long deadline, Process child) { + do { + var descriptor = state.descriptor(); + if (descriptor != null && descriptor.compatible() && state.owned()) { + try { if (!health(descriptor).draining()) return descriptor; } + catch (IOException transientFailure) { /* Listener may be finishing startup. */ } + } + if (child != null && !child.isAlive()) + throw ProtocolException.validation("Project server failed to start (exit " + child.exitValue() + "); inspect " + state.file("startup.log")); + pause(); + } while (System.nanoTime() < deadline); + throw ProtocolException.validation("Project server readiness timed out; no command sent. Inspect " + state.file("startup.log")); + } + public void stop(long timeoutMillis) { + if (timeoutMillis < 1) throw ProtocolException.invalid("Stop timeout must be positive"); + if (!Files.exists(state.directory)) return; + long deadline = System.nanoTime() + timeoutMillis * 1_000_000; + try (var start = state.lock("startup.lock", timeoutMillis)) { + if (start == null) throw ProtocolException.validation("Timed out waiting for server management lock"); + var descriptor = state.descriptor(); + if (!state.owned()) { if (descriptor != null) state.removeDescriptor(descriptor.instance()); return; } + if (descriptor == null) throw ProtocolException.validation("Project server is starting; wait for readiness before stopping"); + if (descriptor.protocol() != ServerIdentity.PROTOCOL) throw ProtocolException.validation("Stop this server with its matching AIE version"); + try { health(descriptor); new ServerConnection(descriptor).call("POST", "/stop", null, ServerProtocol.Health.class); } + catch (IOException failure) { throw ProtocolException.validation("Server is unreachable; no process was killed"); } + waitUnowned(deadline); + } + } + private void waitUnowned(long deadline) { + while (state.owned()) { + if (System.nanoTime() >= deadline) throw ProtocolException.validation("Server is draining; active operations were not killed. Retry after they finish"); + pause(); + } + } + private static void pause() { + try { Thread.sleep(20); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw ProtocolException.validation("Interrupted waiting for project server"); } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerProtocol.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerProtocol.java new file mode 100644 index 0000000..372385f --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerProtocol.java @@ -0,0 +1,49 @@ +package net.intrepid.aiengineering.localserver; + +import java.util.*; +import net.intrepid.aiengineering.filesystem.ProtocolException; + +public final class ServerProtocol { + private ServerProtocol() {} + public record Request(String id, String project, String cwd, List argv, boolean interactive) { + public Request { + identifier(id); + if (project == null || cwd == null || argv == null || argv.isEmpty() || argv.size() > 1024 + || argv.stream().anyMatch(Objects::isNull)) throw ProtocolException.invalid("Invalid command envelope"); + argv = List.copyOf(argv); + } + public String fingerprint() { return ServerIdentity.hash(ServerJson.encode(this)); } + } + public record Health(int protocol, String build, String project, String instance, long pid, + boolean draining, int active, long idleMillis, List requests) {} + public record View(String id, String state, int exitCode, String stdout, String stderr, + int inputSequence, boolean needsInput, boolean cancellationRequested) {} + public record Input(String id, int sequence, String text) { public Input { identifier(id); } } + public record Cancel(String id) { public Cancel { identifier(id); } } + public record Error(int exitCode, String message) {} + /** Offsets are UTF-16 character offsets, matching View and Java's invocation writers. */ + public record Event(String id, String cursor, String kind, int stdoutOffset, int stderrOffset, + String stdout, String stderr, String state, int exitCode, int inputSequence, + boolean needsInput, boolean cancellationRequested) { + public boolean terminal() { return state.equals("COMPLETED") || state.equals("UNKNOWN"); } + } + @FunctionalInterface public interface EventSource extends AutoCloseable { + Event next(String cursor, long timeoutMillis) throws InterruptedException; + @Override default void close() {} + } + public static String identifier(String id) { + if (id == null || !id.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) + throw ProtocolException.invalid("Invalid local request ID"); + return id; + } + public interface Operations extends AutoCloseable { + View submit(Request request); + View get(String id); + View input(Input input); + View cancel(String id); + default EventSource events(String id) { return JobEvents.completed(get(id)); } + int active(); + default List pending() { return List.of(); } + @Override default void close() {} + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/ServerState.java b/src/main/java/net/intrepid/aiengineering/localserver/ServerState.java new file mode 100644 index 0000000..3f541a5 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/ServerState.java @@ -0,0 +1,100 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.*; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.UUID; +import static java.nio.file.StandardOpenOption.*; +import static java.nio.file.LinkOption.NOFOLLOW_LINKS; + +/** Private operational state. No canonical Work or database schema changes. */ +public final class ServerState { + public record Descriptor(int protocol, String build, String root, String instance, long pid, int port, String token) { + public Descriptor { + if (protocol < 1 || build == null || !build.matches("[a-f0-9]{64}") || root == null + || !Path.of(root).isAbsolute() || pid < 1 || port < 1 || port > 65535 + || token == null || !token.matches("[a-f0-9]{64}")) throw ProtocolException.invalid("Invalid server descriptor"); + UUID.fromString(instance); + } + public boolean compatible() { return protocol == ServerIdentity.PROTOCOL && build.equals(ServerIdentity.BUILD); } + } + public final Path root; + public final Path directory; + public ServerState(Path root) { + this.root = Filespace.io(() -> root.toRealPath()); + directory = Filespace.resolve(this.root, ".ai-engineering/.local/server"); + } + public void initialize() { + Filespace.resolve(root, ".ai-engineering/.local/server"); + Filespace.directory(directory); permissions(directory, "rwx------"); + } + public Path file(String name) { return Filespace.resolve(root, ".ai-engineering/.local/server/" + name); } + public Descriptor descriptor() { + Path path = file("endpoint.json"); + if (!Files.exists(path, NOFOLLOW_LINKS)) return null; + if (!Files.isRegularFile(path, NOFOLLOW_LINKS) || Filespace.io(() -> Files.size(path)) > 8192) + throw ProtocolException.validation("Invalid server descriptor; inspect " + path); + var descriptor = ServerJson.decode(Filespace.read(path), Descriptor.class); + if (!descriptor.root().equals(root.toString())) throw ProtocolException.validation("Server descriptor belongs to another project"); + return descriptor; + } + public void publish(Descriptor descriptor) { write(file("endpoint.json"), ServerJson.encode(descriptor)); } + public void removeDescriptor(String instance) { + var current = descriptor(); + if (current != null && current.instance().equals(instance)) Filespace.io(() -> Files.deleteIfExists(file("endpoint.json"))); + } + public Lease lock(String name, long timeoutMillis) { + initialize(); + return Filespace.io(() -> { + var channel = FileChannel.open(file(name), CREATE, WRITE, NOFOLLOW_LINKS); + permissions(file(name), "rw-------"); + long deadline = System.nanoTime() + timeoutMillis * 1_000_000; + try { + do { + try { var lock = channel.tryLock(); if (lock != null) return new Lease(channel, lock); } + catch (OverlappingFileLockException busy) { /* Same-process contender is also an owner. */ } + if (System.nanoTime() >= deadline) break; + try { Thread.sleep(20); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("Interrupted waiting for server lock"); } + } while (true); + } catch (Throwable failure) { channel.close(); throw failure; } + channel.close(); return null; + }); + } + public boolean owned() { + try (var lease = lock("owner.lock", 0)) { return lease == null; } + } + public static final class Lease implements AutoCloseable { + private final FileChannel channel; + private final FileLock lock; + private Lease(FileChannel channel, FileLock lock) { this.channel = channel; this.lock = lock; } + @Override public void close() { Filespace.io(() -> { try { lock.release(); } finally { channel.close(); } return null; }); } + } + public static void write(Path path, String value) { + Filespace.io(() -> { + if (Files.isSymbolicLink(path)) throw ProtocolException.invalid("Symlink rejected: " + path); + Path temporary = path.resolveSibling("." + path.getFileName() + "." + UUID.randomUUID() + ".tmp"); + try { + // Create private before writing capability tokens or command results. + try (var channel = FileChannel.open(temporary, CREATE_NEW, WRITE, NOFOLLOW_LINKS)) { + permissions(temporary, "rw-------"); + var bytes = ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)); + while (bytes.hasRemaining()) channel.write(bytes); + channel.force(true); + } + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + try (var directory = FileChannel.open(path.getParent(), READ)) { directory.force(true); } + } finally { Files.deleteIfExists(temporary); } + return null; + }); + } + static void permissions(Path path, String mode) { + try { Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); } + catch (UnsupportedOperationException ignored) { /* Windows inherits the user's private project ACL. */ } + catch (IOException failure) { throw new ProtocolException(1, "Cannot protect local server state: " + path); } + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/SseFrames.java b/src/main/java/net/intrepid/aiengineering/localserver/SseFrames.java new file mode 100644 index 0000000..8657225 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/SseFrames.java @@ -0,0 +1,17 @@ +package net.intrepid.aiengineering.localserver; + +/** ASCII JSON escapes preserve UTF-16 offsets, including surrogate pairs split across writer calls. */ +public final class SseFrames { + private static final char[] HEX="0123456789abcdef".toCharArray(); + private SseFrames() {} + public static String encode(ServerProtocol.Event event) { + String json=ServerJson.encode(event); + var data=new StringBuilder(json.length()); + for(int i=0;i>>12]).append(HEX[(c>>>8)&15]).append(HEX[(c>>>4)&15]).append(HEX[c&15]); + } + return "id: "+event.cursor()+"\nevent: "+event.kind()+"\ndata: "+data+"\n\n"; + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/SseReader.java b/src/main/java/net/intrepid/aiengineering/localserver/SseReader.java new file mode 100644 index 0000000..b83a98b --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/SseReader.java @@ -0,0 +1,58 @@ +package net.intrepid.aiengineering.localserver; + +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.*; +import java.util.Set; + +/** Incremental SSE framing; a blank comment frame returns null, an incomplete/disconnected frame throws. */ +public final class SseReader implements AutoCloseable { + private static final int MAX_FRAME_CHARS=128*1024*1024; + private static final Set KINDS=Set.of("snapshot","stdout","stderr","progress","input-required","completed","unknown"); + private final BufferedReader reader; + private final String requestId; + private boolean skipLf; + private int consumed; + public SseReader(Reader reader,String requestId) { this.reader=new BufferedReader(reader);this.requestId=ServerProtocol.identifier(requestId); } + private String line() throws IOException { + var line=new StringBuilder(); + while(true) { + int value=reader.read(); + if(value<0)throw new EOFException("SSE disconnected before a terminal event for "+requestId); + if(skipLf && value=='\n'){skipLf=false;continue;}skipLf=false; + if(++consumed>MAX_FRAME_CHARS)throw ProtocolException.validation("SSE frame exceeds 128 Mi characters"); + if(value=='\r'){skipLf=true;return line.toString();} + if(value=='\n')return line.toString(); + line.append((char)value); + } + } + public ServerProtocol.Event next() throws IOException { + consumed=0;String cursor=null,kind=null;var data=new StringBuilder(); + while(true) { + String line=line(); + if(line.isEmpty()) { + if(data.isEmpty())return null; + var event=ServerJson.decode(data.toString(),ServerProtocol.Event.class); + JobEvents.validateCursor(event.cursor()); + if(!requestId.equals(event.id()) || event.cursor()==null || !event.cursor().equals(cursor) + || kind==null || !KINDS.contains(kind) || !kind.equals(event.kind()) || event.stdout()==null || event.stderr()==null + || event.stdoutOffset()<0 || event.stderrOffset()<0 || event.inputSequence()<0 || event.state()==null + || !Set.of("QUEUED","RUNNING","COMPLETED","UNKNOWN").contains(event.state()) + || (event.terminal() && event.exitCode()<0) || (event.needsInput() && event.inputSequence()==0) + || (kind.equals("completed") && !event.state().equals("COMPLETED")) + || (kind.equals("unknown") && !event.state().equals("UNKNOWN"))) + throw ProtocolException.validation("Invalid SSE event identity/state for "+requestId); + return event; + } + if(line.startsWith(":"))continue; + int colon=line.indexOf(':');String field=colon<0?line:line.substring(0,colon); + String value=colon<0?"":line.substring(colon+1);if(value.startsWith(" "))value=value.substring(1); + switch(field) { + case "id" -> cursor=value; + case "event" -> kind=value; + case "data" -> {if(!data.isEmpty())data.append('\n');data.append(value);} + default -> { /* Other standard fields do not control this CLI's bounded reconnection policy. */ } + } + } + } + @Override public void close() throws IOException {reader.close();} +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/SseStreams.java b/src/main/java/net/intrepid/aiengineering/localserver/SseStreams.java new file mode 100644 index 0000000..2d136a7 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/SseStreams.java @@ -0,0 +1,99 @@ +package net.intrepid.aiengineering.localserver; + +import com.sun.net.httpserver.HttpExchange; +import net.intrepid.aiengineering.filesystem.ProtocolException; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.*; + +/** Dedicated, bounded subscriptions. Interrupting a stalled JDK SocketChannel writer closes its channel. */ +public final class SseStreams implements AutoCloseable { + public static final int MAX_STREAMS=16, MAX_PER_JOB=2; + public static final long HEARTBEAT_MILLIS=1000, WRITE_TIMEOUT_MILLIS=2000, DRAIN_MILLIS=1000; + private final ExecutorService workers=new ThreadPoolExecutor(0,MAX_STREAMS,30,TimeUnit.SECONDS, + new SynchronousQueue<>(),Thread.ofPlatform().daemon().name("aie-sse-",0).factory()); + private final ScheduledExecutorService watchdog=Executors.newSingleThreadScheduledExecutor( + Thread.ofPlatform().daemon().name("aie-sse-watchdog").factory()); + private final Set subscribers=new HashSet<>(); + private volatile boolean closed; + private long drainingSince; + public SseStreams() { watchdog.scheduleWithFixedDelay(this::expireWriters,100,100,TimeUnit.MILLISECONDS); } + public synchronized int active() { return subscribers.size(); } + public synchronized boolean drained() { + if(subscribers.isEmpty()) return true; + if(drainingSince==0) drainingSince=System.nanoTime(); + return System.nanoTime()-drainingSince>=DRAIN_MILLIS*1_000_000; + } + public void open(HttpExchange exchange,String id,String cursor,ServerProtocol.EventSource source) { + JobEvents.validateCursor(cursor); + var subscriber=new Subscriber(exchange,id,cursor,source); + synchronized(this) { + if(closed || subscribers.size()>=MAX_STREAMS + || subscribers.stream().filter(value->value.id.equals(id)).count()>=MAX_PER_JOB) { + source.close(); throw ProtocolException.validation("SSE subscriber capacity exceeded; job remains recoverable: "+id); + } + subscribers.add(subscriber); + try { workers.execute(subscriber); } + catch(RejectedExecutionException busy) { + subscribers.remove(subscriber); source.close(); + throw ProtocolException.validation("SSE workers busy; job remains recoverable: "+id); + } + } + } + private synchronized void expireWriters() { + long now=System.nanoTime(); + for(var subscriber:subscribers) { + long since=subscriber.writingSince; Thread writer=subscriber.thread; + if(since!=0 && now-since>WRITE_TIMEOUT_MILLIS*1_000_000 && writer!=null) writer.interrupt(); + } + } + private final class Subscriber implements Runnable { + final HttpExchange exchange; + final String id; + final ServerProtocol.EventSource source; + String cursor; + volatile Thread thread; + volatile long writingSince; + Subscriber(HttpExchange exchange,String id,String cursor,ServerProtocol.EventSource source) { + this.exchange=exchange;this.id=id;this.cursor=cursor;this.source=source; + } + void write(String frame) throws IOException { + writingSince=System.nanoTime(); + try { + exchange.getResponseBody().write(frame.getBytes(StandardCharsets.UTF_8)); + exchange.getResponseBody().flush(); + } finally { writingSince=0; } + } + @Override public void run() { + thread=Thread.currentThread(); + try { + if(closed) return; + exchange.getResponseHeaders().set("Content-Type","text/event-stream; charset=utf-8"); + exchange.getResponseHeaders().set("Cache-Control","no-store"); + writingSince=System.nanoTime(); + try { exchange.sendResponseHeaders(200,0); } finally { writingSince=0; } + while(!closed) { + var event=source.next(cursor,HEARTBEAT_MILLIS); + if(event==null) { write(": heartbeat\n\n"); continue; } + write(SseFrames.encode(event)); cursor=event.cursor(); + if(event.terminal()) return; + } + } catch(InterruptedException interrupted) { Thread.currentThread().interrupt(); } + catch(IOException | RuntimeException disconnected) { /* Detaching a subscriber never cancels or replays its job. */ } + finally { + writingSince=System.nanoTime(); + try { exchange.close(); } + finally { source.close(); synchronized(SseStreams.this) { subscribers.remove(this); } } + } + } + } + @Override public void close() { + synchronized(this) { + if(closed) return; + closed=true; + for(var subscriber:subscribers) if(subscriber.thread!=null) subscriber.thread.interrupt(); + } + workers.shutdownNow(); watchdog.shutdown(); + } +} diff --git a/src/main/java/net/intrepid/aiengineering/localserver/package-info.java b/src/main/java/net/intrepid/aiengineering/localserver/package-info.java new file mode 100644 index 0000000..6d78659 --- /dev/null +++ b/src/main/java/net/intrepid/aiengineering/localserver/package-info.java @@ -0,0 +1,2 @@ +@org.springframework.modulith.ApplicationModule(allowedDependencies = {"cli", "filesystem", "project"}) +package net.intrepid.aiengineering.localserver; diff --git a/src/main/resources/protocol/README.md b/src/main/resources/protocol/README.md index f47d2a8..2f33c57 100644 --- a/src/main/resources/protocol/README.md +++ b/src/main/resources/protocol/README.md @@ -8,7 +8,25 @@ and Git availability are optional. Preserve project instructions outside AIE's b ## Starting or continuing work -Use `ai-engineering` (or its installed alias `aie`). No server or model API is needed. +Use `ai-engineering` (or its installed alias `aie`). A lightweight client starts and +reuses a local Spring server for each project; no separately installed service or +model API is required. `aie start` waits for readiness and `aie stop` drains active +operations. Idle servers stop after 30 minutes by default; use +`aie start --idle-timeout-seconds N` to configure that instance. A normal command +can start the server again. `aie server status` inspects the process; `aie status` +continues to inspect engineering Works. Help, version and initialization are local. + +Pending operations use an authenticated SSE event stream, with bounded cursor +reconnection instead of periodic status polling. Immediate results remain JSON. +Input and cancellation use explicit POST requests; losing an event stream does +not cancel or resubmit its job. Request progress goes to stderr; stdout retains +the requested format and exit codes. Pending operations expose a request ID. +`aie server request ID` recovers its +result and `aie server cancel ID` requests cooperative cancellation. An UNKNOWN +outcome after interruption requires inspection of effects before another mutation; +never infer rollback or replay the command automatically. Operational descriptors, +locks and results live privately under `.ai-engineering/.local/server/` and are not +a second authority for Work memory. Preserve them while outcomes need recovery. 1. Run `aie status --format json` and `aie next-actions --format json`. 2. Locate the requested Work, or create one with `aie work create "Title"` after diff --git a/src/test/java/net/intrepid/aiengineering/DiscussionImportTest.java b/src/test/java/net/intrepid/aiengineering/DiscussionImportTest.java index 9518f5b..60b419a 100644 --- a/src/test/java/net/intrepid/aiengineering/DiscussionImportTest.java +++ b/src/test/java/net/intrepid/aiengineering/DiscussionImportTest.java @@ -17,6 +17,7 @@ import java.util.*; import static net.intrepid.aiengineering.legacyimport.DiscussionImport.*; import static org.assertj.core.api.Assertions.*; +@org.junit.jupiter.api.extension.ExtendWith(LocalServerCleanup.class) class DiscussionImportTest { @TempDir Path temp; Path root, alpha, beta; diff --git a/src/test/java/net/intrepid/aiengineering/InvocationPolicyTest.java b/src/test/java/net/intrepid/aiengineering/InvocationPolicyTest.java new file mode 100644 index 0000000..c3c27d2 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/InvocationPolicyTest.java @@ -0,0 +1,46 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.cli.EngineeringCli; +import net.intrepid.aiengineering.localserver.InvocationPolicy; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.io.*; +import static org.assertj.core.api.Assertions.*; + +class InvocationPolicyTest { + @TempDir Path root; + @Test void parsingDoesNotExecuteAndDoesNotMistakeArgumentValuesForCommands() { + var cli = new EngineeringCli(root); + var parser = cli.commandLine(new PrintWriter(new StringWriter()), new PrintWriter(new StringWriter())); + var parsed = parser.parseArgs("work", "create", "init", "--goal", "guide"); + assertThat(InvocationPolicy.path(parsed)).isEqualTo("work create"); + assertThat(InvocationPolicy.local(parsed)).isFalse(); + assertThat(InvocationPolicy.readOnly(parsed)).isFalse(); + assertThat(root.resolve(".ai-engineering")).doesNotExist(); + assertThat(InvocationPolicy.local(parser.parseArgs("work", "show", "--help"))).isTrue(); + assertThat(InvocationPolicy.readOnly(parser.parseArgs("work", "show", "WRK-0001"))).isTrue(); + assertThat(InvocationPolicy.readOnly(parser.parseArgs("artifact", "recover", "WRK-0001"))).isFalse(); + } + @Test void selectedBranchPreservesLiteralOptionsGlobalPathsAndNestedCommands() { + var sink=new PrintWriter(Writer.nullWriter()); + for (String[] args:new String[][] { + {"work","create","init","--goal","guide"}, + {"--project",root.toString(),"work","show","WRK-0001","--format","json"}, + {"work","show","WRK-0001","--project",root.toString()}, + {"discussion","add","WRK-0001","--text","work show --help"}, + {"plan","step","status","WRK-0001","PLN-0001","TSK-0001","ACTIVE","--by","test","--reason","fixture"}, + {"init","--name","Fixture"}, {"work","show","--help"} + }) { + var full=new EngineeringCli(root).commandLine(sink,sink).parseArgs(args); + var quick=new EngineeringCli(root).commandLineFor(sink,sink,args).parseArgs(args); + assertThat(InvocationPolicy.path(quick)).isEqualTo(InvocationPolicy.path(full)); + assertThat(InvocationPolicy.local(quick)).isEqualTo(InvocationPolicy.local(full)); + } + var cli=new EngineeringCli(root); + var quick=cli.commandLineFor(sink,sink,"work","show","WRK-0001"); + assertThat(quick.getSubcommands()).containsOnlyKeys("work"); + assertThat(quick.getSubcommands().get("work").getSubcommands()).containsOnlyKeys("show"); + assertThat(root.resolve(".ai-engineering")).doesNotExist(); + } +} diff --git a/src/test/java/net/intrepid/aiengineering/JobEventsTest.java b/src/test/java/net/intrepid/aiengineering/JobEventsTest.java new file mode 100644 index 0000000..e84899f --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/JobEventsTest.java @@ -0,0 +1,46 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import org.junit.jupiter.api.Test; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import static org.assertj.core.api.Assertions.*; + +class JobEventsTest { + private final String id=UUID.randomUUID().toString(); + private ServerProtocol.View view(String out,String state) { return new ServerProtocol.View(id,state,state.equals("COMPLETED")?0:-1,out,"",0,false,false); } + @Test void incrementalEventsResumeAndExpiredCursorsHaveExplicitSnapshots() throws Exception { + var current=new AtomicReference<>(view("","RUNNING")); + var events=new JobEvents(new Object(),current::get); + var initial=events.next(null,0); assertThat(initial.kind()).isEqualTo("snapshot"); + current.set(view("café 😀\n","RUNNING")); + events.publish("stdout",0,0,"café 😀\n","",view("","RUNNING")); + var delta=events.next(initial.cursor(),0); + assertThat(delta.kind()).isEqualTo("stdout"); assertThat(delta.stdout()).isEqualTo("café 😀\n"); + assertThat(events.next(delta.cursor(),0)).isNull(); + for (int i=0;ievents.next("invalid",0)).hasMessageContaining("cursor"); + } + @Test void notificationWakesWaitingSubscriberAndCompletionIsRecoverable() throws Exception { + var current=new AtomicReference<>(view("","RUNNING")); var monitor=new Object(); + var events=new JobEvents(monitor,current::get); var cursor=events.next(null,0).cursor(); + try (var worker=Executors.newSingleThreadExecutor()) { + var next=worker.submit(()->events.next(cursor,10000)); + current.set(view("done","COMPLETED")); + events.publish("completed",0,0,"done","",current.get()); + assertThat(next.get(2,TimeUnit.SECONDS).terminal()).isTrue(); + } + var restarted=JobEvents.completed(current.get()).next(cursor,0); + assertThat(restarted.kind()).isEqualTo("snapshot"); assertThat(restarted.stdout()).isEqualTo("done"); + assertThat(restarted.terminal()).isTrue(); + } + @Test void replayCharactersAreBoundedIndependentlyOfEventCount() throws Exception { + var current=view("full snapshot","RUNNING");var events=new JobEvents(new Object(),()->current); + String cursor=events.next(null,0).cursor(); + for(int i=0;i<18;i++)events.publish("stdout",i*JobEvents.CHUNK_CHARS,0,"x".repeat(JobEvents.CHUNK_CHARS),"",view("","RUNNING")); + assertThat(events.next(cursor,0).kind()).isEqualTo("snapshot"); + } +} diff --git a/src/test/java/net/intrepid/aiengineering/LocalServerCleanup.java b/src/test/java/net/intrepid/aiengineering/LocalServerCleanup.java new file mode 100644 index 0000000..4800555 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/LocalServerCleanup.java @@ -0,0 +1,27 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.ServerManager; +import org.junit.jupiter.api.extension.*; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.util.List; + +/** Stop fixture-owned daemons before JUnit removes their project directories. */ +public final class LocalServerCleanup implements AfterEachCallback { + @Override public void afterEach(ExtensionContext context) throws Exception { + Object instance = context.getRequiredTestInstance(); + for (var field : instance.getClass().getDeclaredFields()) { + if (!field.isAnnotationPresent(TempDir.class) || field.getType() != Path.class) continue; + field.setAccessible(true); Path temporary = (Path) field.get(instance); + if (temporary == null || !Files.isDirectory(temporary)) continue; + List endpoints; + try (var files = Files.walk(temporary)) { + endpoints = files.filter(path -> path.endsWith(Path.of(".ai-engineering/.local/server/endpoint.json"))).toList(); + } + for (Path endpoint : endpoints) { + Path project = endpoint.getParent().getParent().getParent().getParent(); + new ServerManager(project,List.of()).stop(10000); + } + } + } +} diff --git a/src/test/java/net/intrepid/aiengineering/LocalServerProcessTest.java b/src/test/java/net/intrepid/aiengineering/LocalServerProcessTest.java new file mode 100644 index 0000000..b4c7746 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/LocalServerProcessTest.java @@ -0,0 +1,147 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.TimeUnit; +import static org.assertj.core.api.Assertions.*; + +class LocalServerProcessTest { + @TempDir Path root; + private ServerManager manager() { return new ServerManager(root, ServerLaunch.jar(Path.of(System.getProperty("cli.jar")))); } + @AfterEach void cleanup() { if (Files.exists(root.resolve(".ai-engineering"))) manager().stop(10000); } + private String cli(Path cwd, String... args) throws Exception { + var command=new ArrayList<>(ServerLaunch.jar(Path.of(System.getProperty("cli.jar")))); command.addAll(List.of(args)); + Path stdout=Files.createTempFile("aie-client-", ".out"), stderr=Files.createTempFile("aie-client-", ".err"); + try { + var process=new ProcessBuilder(command).directory(cwd.toFile()).redirectOutput(stdout.toFile()).redirectError(stderr.toFile()).start(); + process.getOutputStream().close(); + boolean exited=process.waitFor(30,TimeUnit.SECONDS); + if (!exited) process.destroyForcibly(); + assertThat(exited).as("Client must finish").isTrue(); + assertThat(process.exitValue()).as(Files.readString(stderr)+Files.readString(stdout)).isZero(); + return Files.readString(stdout); + } finally { Files.deleteIfExists(stdout); Files.deleteIfExists(stderr); } + } + @Test void lightweightClientsReuseServerAndPreserveWorkingDirectoryAndJson() throws Exception { + assertThat(cli(root,"--version").strip()).isEqualTo("ai-engineering 0.1.0"); + assertThat(root.resolve(".ai-engineering")).doesNotExist(); + cli(root,"init","--name","Server project"); + assertThat(root.resolve(".ai-engineering/.local/server/endpoint.json")).doesNotExist(); + cli(root,"start"); var first=manager().state().descriptor(); + cli(root,"start"); assertThat(manager().state().descriptor().instance()).isEqualTo(first.instance()); + cli(root,"work","create","Café — preserved"); + Path nested=Files.createDirectories(root.resolve("nested/deep")); Files.writeString(nested.resolve("note.txt"),"UTF-8 café\n"); + cli(nested,"discussion","add","WRK-0001","--text-file","note.txt"); + assertThat(cli(nested,"work","show","WRK-0001","--format","json")).startsWith("{").contains("Café — preserved"); + assertThat(cli(root,"discussion","list","WRK-0001","--format","json")).contains("UTF-8 café"); + assertThat(manager().state().descriptor().instance()).isEqualTo(first.instance()); + cli(root,"stop"); cli(root,"stop"); assertThat(manager().state().descriptor()).isNull(); + assertThat(cli(root,"work","show","WRK-0001","--format","json")).contains("WRK-0001"); + assertThat(manager().state().descriptor().instance()).isNotEqualTo(first.instance()); + } + @Test void concurrentStartersUseOneOwnerAndIdleTimeoutRemainsConfigurable() throws Exception { + cli(root,"init","--name","Concurrent starters"); + try (var workers=java.util.concurrent.Executors.newFixedThreadPool(3)) { + var calls=new ArrayList>(); + for (int i=0;i<3;i++) calls.add(workers.submit(() -> manager().ensure(20000,1000L).instance())); + var instances=new HashSet(); + for (var call:calls) instances.add(call.get(25,TimeUnit.SECONDS)); + assertThat(instances).hasSize(1); + } + long deadline=System.nanoTime()+5_000_000_000L; + while (manager().state().descriptor()!=null && System.nanoTime()(ServerLaunch.jar(previous)); + launch.addAll(List.of(ServerLaunch.INTERNAL,root.toString(),"60000")); + var child=new ProcessBuilder(launch).directory(root.toFile()).redirectErrorStream(true) + .redirectOutput(root.resolve("previous.log").toFile()).start(); + child.getOutputStream().close(); + try { + long deadline=System.nanoTime()+15_000_000_000L; + ServerState.Descriptor old; + while ((old=manager().state().descriptor())==null && System.nanoTime() manager().ensure(20000,null)); + while (!connection.health().draining() && System.nanoTime()new LocalClient(root,input,new PrintWriter(stdout),new PrintWriter(stderr),true) + .execute("survey","ask","WRK-0001","SVY-0001")); + try{ + assertThat(reading.await(15,TimeUnit.SECONDS)).isTrue(); + var old=manager().state().descriptor();var pending=new ServerConnection(old).health().requests();assertThat(pending).hasSize(1); + var child=ProcessHandle.of(old.pid()).orElseThrow();child.destroyForcibly();child.onExit().get(10,TimeUnit.SECONDS); + var restarted=manager().ensure(20000,null);answer.countDown(); + assertThat(result.get(15,TimeUnit.SECONDS)).isEqualTo(4); + assertThat(stderr.toString()).contains("unknown outcome"); + assertThat(new ServerConnection(restarted).call("GET","/requests/"+pending.getFirst(),null,ServerProtocol.View.class).state()).isEqualTo("UNKNOWN"); + assertThat(cli(root,"survey","show","WRK-0001","SVY-0001")).contains("Pending answer"); + }finally{answer.countDown();result.cancel(true);} + }finally{answer.countDown();} + } +} diff --git a/src/test/java/net/intrepid/aiengineering/PlanDecisionPromotionTest.java b/src/test/java/net/intrepid/aiengineering/PlanDecisionPromotionTest.java index e024fa9..a781017 100644 --- a/src/test/java/net/intrepid/aiengineering/PlanDecisionPromotionTest.java +++ b/src/test/java/net/intrepid/aiengineering/PlanDecisionPromotionTest.java @@ -11,6 +11,7 @@ import java.nio.file.*; import java.util.*; import static org.assertj.core.api.Assertions.*; +@org.junit.jupiter.api.extension.ExtendWith(LocalServerCleanup.class) class PlanDecisionPromotionTest { @TempDir Path root; private String output; diff --git a/src/test/java/net/intrepid/aiengineering/ProcessContinuityTest.java b/src/test/java/net/intrepid/aiengineering/ProcessContinuityTest.java index cf167ca..9da889a 100644 --- a/src/test/java/net/intrepid/aiengineering/ProcessContinuityTest.java +++ b/src/test/java/net/intrepid/aiengineering/ProcessContinuityTest.java @@ -7,7 +7,8 @@ import java.util.*; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.*; -/** Separate operating-system processes prove there is no hidden in-memory continuity. */ +/** Independent clients and explicit daemon restart preserve canonical continuity. */ +@org.junit.jupiter.api.extension.ExtendWith(LocalServerCleanup.class) class ProcessContinuityTest { @TempDir Path root; private String cli(String... args) throws Exception { @@ -20,16 +21,16 @@ class ProcessContinuityTest { var command = new ArrayList<>(List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString(), "-jar", System.getProperty("cli.jar"))); command.addAll(List.of(args)); - Path log = Files.createTempFile("aie-process-", ".log"); + Path log = Files.createTempFile("aie-process-", ".log"), errors = Files.createTempFile("aie-process-", ".err"); try { - var builder = new ProcessBuilder(command).directory(root.toFile()).redirectErrorStream(true).redirectOutput(log.toFile()); + var builder = new ProcessBuilder(command).directory(root.toFile()).redirectError(errors.toFile()).redirectOutput(log.toFile()); if (withoutGit) builder.environment().put("PATH", root.resolve("no-installed-tools").toString()); var process = builder.start(); boolean exited = process.waitFor(30, TimeUnit.SECONDS); if (!exited) process.destroyForcibly(); - assertThat(exited).as("CLI must terminate without a server").isTrue(); - String result = Files.readString(log); assertThat(process.exitValue()).as(result).isZero(); return result; - } finally { Files.deleteIfExists(log); } + assertThat(exited).as("CLI must terminate independently of the server").isTrue(); + String result = Files.readString(log); assertThat(process.exitValue()).as(result + Files.readString(errors)).isZero(); return result; + } finally { Files.deleteIfExists(log); Files.deleteIfExists(errors); } } @Test void simpleProjectWorksAcrossProcessesWithoutGitOnPath() throws Exception { Path source = Files.writeString(root.resolve("main.txt"), "Existing project\n"); @@ -43,6 +44,7 @@ class ProcessContinuityTest { cliWithoutGit("work", "update", "WRK-0001", "--goal", "Continue from recorded evidence", "--constraint", "Keep existing sources", "--acceptance", "Context reloads in another process"); String context = cliWithoutGit("work", "context", "WRK-0001", "--format", "json"); + cliWithoutGit("stop"); // The next client must reconstruct canonical memory after daemon restart too. assertThat(cliWithoutGit("work", "context", "WRK-0001", "--format", "json")).isEqualTo(context) .contains("Continue from recorded evidence", "Keep existing sources", "Context reloads in another process", "Read from UTF-8.", "\"repositories\" : [ ]", "Initial source evidence", "Pilot the protocol"); diff --git a/src/test/java/net/intrepid/aiengineering/ProjectServerTest.java b/src/test/java/net/intrepid/aiengineering/ProjectServerTest.java new file mode 100644 index 0000000..2614f72 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/ProjectServerTest.java @@ -0,0 +1,45 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.assertj.core.api.Assertions.*; + +class ProjectServerTest { + @TempDir Path root; + private static class Operations implements ServerProtocol.Operations { + final AtomicInteger calls = new AtomicInteger(); + public ServerProtocol.View submit(ServerProtocol.Request request) { calls.incrementAndGet(); return get(request.id()); } + public ServerProtocol.View get(String id) { return new ServerProtocol.View(id,"COMPLETED",0,"café\n","",0,false,false); } + public ServerProtocol.View input(ServerProtocol.Input input) { return get(input.id()); } + public ServerProtocol.View cancel(String id) { return get(id); } + public int active() { return 0; } + } + @Test void authenticatesInstanceProjectAndDrainsWithoutLeakingTokens() throws Exception { + var operations = new Operations(); + try (var server = new ProjectServer(new ServerState(root), 60000, operations)) { + var descriptor = server.descriptor(); var connection = new ServerConnection(descriptor); + assertThat(connection.health().project()).isEqualTo(root.toRealPath().toString()); + var wrong = new ServerState.Descriptor(1, descriptor.build(), descriptor.root(), descriptor.instance(), + descriptor.pid(), descriptor.port(), "0".repeat(64)); + assertThatThrownBy(() -> new ServerConnection(wrong).health()).hasMessageContaining("authentication"); + String id = UUID.randomUUID().toString(); + var request = new ServerProtocol.Request(id, descriptor.root(), root.toString(), List.of("work","list"),false); + assertThat(connection.call("POST","/execute",request,ServerProtocol.View.class).stdout()).isEqualTo("café\n"); + assertThat(operations.calls).hasValue(1); + var invalid = new ServerProtocol.Request(id, root.resolve("other").toString(),root.toString(),List.of("status"),false); + assertThatThrownBy(() -> connection.call("POST","/execute",invalid,ServerProtocol.View.class)).hasMessageContaining("another project"); + connection.call("POST","/stop",null,ServerProtocol.Health.class); + assertThat(server.await(3000)).isTrue(); + } + assertThat(new ServerState(root).descriptor()).isNull(); + } + @Test void expiresIdleServer() throws Exception { + try (var server = new ProjectServer(new ServerState(root), 60, new Operations())) { + assertThat(server.await(3000)).isTrue(); + } + } +} diff --git a/src/test/java/net/intrepid/aiengineering/RequestJobsTest.java b/src/test/java/net/intrepid/aiengineering/RequestJobsTest.java new file mode 100644 index 0000000..32801cf --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/RequestJobsTest.java @@ -0,0 +1,107 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.cli.EngineeringCli; +import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.project.ProjectService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.assertj.core.api.Assertions.*; + +class RequestJobsTest { + @TempDir Path root; + private ServerProtocol.Request request(String... argv) throws IOException { + return new ServerProtocol.Request(UUID.randomUUID().toString(), root.toRealPath().toString(),root.toRealPath().toString(),List.of(argv),false); + } + private ServerProtocol.View done(RequestJobs jobs, ServerProtocol.View view) { + long deadline = System.nanoTime() + 10_000_000_000L; + while (!Set.of("COMPLETED","UNKNOWN").contains(view.state()) && System.nanoTime() < deadline) view = jobs.get(view.id()); + assertThat(view.state()).isEqualTo("COMPLETED"); return view; + } + @Test void mutationDeduplicatesAndResultSurvivesRestartWithoutChangingCanonicalSchema() throws Exception { + new ProjectService().initializeSqlite(root,"Requests"); var state = new ServerState(root); + var request = request("work","create","Only once"); + try (var jobs = new RequestJobs(state)) { + var first = done(jobs,jobs.submit(request)); assertThat(first.exitCode()).isZero(); + assertThat(jobs.submit(request).stdout()).isEqualTo(first.stdout()); + var different = new ServerProtocol.Request(request.id(),request.project(),request.cwd(),List.of("work","create","Other"),false); + assertThatThrownBy(() -> jobs.submit(different)).hasMessageContaining("different input"); + } + try (var jobs = new RequestJobs(state)) { + assertThat(jobs.submit(request).state()).isEqualTo("COMPLETED"); + var listing = done(jobs,jobs.submit(request("work","list","--format","json"))); + assertThat(listing.stdout()).contains("WRK-0001").doesNotContain("WRK-0002"); + } + } + @Test void interruptedIntentIsUnknownAndNeverReexecuted() throws Exception { + new ProjectService().initializeLegacy(root,"Unknown"); var state = new ServerState(root); + var request = request("work","create","Not replayed"); var executed = new AtomicInteger(); + try (var jobs = new RequestJobs(state,(r,in,out,err) -> { executed.incrementAndGet(); return 0; })) { + ServerState.write(state.file("requests/"+request.id()+".json"),ServerJson.encode(new RequestJobs.Receipt( + request.id(),request.fingerprint(),"RUNNING",-1,"","",false))); + assertThat(jobs.submit(request).state()).isEqualTo("UNKNOWN"); + assertThat(jobs.get(request.id()).stderr()).contains("unknown"); + assertThat(executed).hasValue(0); + } + } + @Test void interactiveJobDoesNotBlockReadsAndCanBeCancelledWithoutClaimingRollback() throws Exception { + new ProjectService().initializeLegacy(root,"Input"); + var cli = new EngineeringCli(root); var out = new PrintWriter(Writer.nullWriter()); + assertThat(cli.execute(out,out,"work","create","Question")).isZero(); + assertThat(cli.execute(out,out,"survey","create","WRK-0001","--title","Choice")).isZero(); + assertThat(cli.execute(out,out,"survey","question","WRK-0001","SVY-0001","--text","Choose","--option","One","--option","Two")).isZero(); + var request = request("survey","ask","WRK-0001","SVY-0001"); + request = new ServerProtocol.Request(request.id(),request.project(),request.cwd(),request.argv(),true); + try (var jobs = new RequestJobs(new ServerState(root))) { + var waiting = jobs.submit(request); + long deadline = System.nanoTime()+5_000_000_000L; + while (!waiting.needsInput() && System.nanoTime() { + if (r.argv().getFirst().equals("agent")) Thread.sleep(10000); + return 0; + })) { + var pending=jobs.submit(request("agent","run","WRK-0001","--task","Synthetic wait")); + assertThat(done(jobs,jobs.submit(request("work","list"))).exitCode()).isZero(); + jobs.cancel(pending.id()); var cancelled=done(jobs,jobs.get(pending.id())); + assertThat(cancelled.cancellationRequested()).isTrue(); assertThat(cancelled.exitCode()).isNotZero(); + } + } + @Test void completedReadResultsRemainRecoverableAfterMemoryCacheEviction() throws Exception { + new ProjectService().initializeLegacy(root,"Read results"); + try (var jobs=new RequestJobs(new ServerState(root),(r,in,out,err) -> { out.print(r.id()); return 0; })) { + var first=request("work","list"); done(jobs,jobs.submit(first)); + for (int i=0;i<66;i++) done(jobs,jobs.submit(request("work","list"))); + assertThat(jobs.get(first.id()).stdout()).isEqualTo(first.id()); + assertThat(jobs.submit(first).state()).isEqualTo("COMPLETED"); + } + } + @Test void envelopeCannotSelectAnotherProjectUsingGlobalOptions() throws Exception { + new ProjectService().initializeLegacy(root,"Bound project"); + Path other=Files.createDirectories(root.resolve("other")); new ProjectService().initializeLegacy(other,"Other"); + try (var jobs=new RequestJobs(new ServerState(root))) { + var foreign=request("--project",other.toString(),"work","create","Wrong target"); + assertThatThrownBy(() -> jobs.submit(foreign)).hasMessageContaining("another project"); + assertThat(Files.list(other.resolve(".ai-engineering/works")).findAny()).isEmpty(); + } + } + @Test void outputCanContainAnExistingMaximumSizeNotePlusContext() throws Exception { + new ProjectService().initializeLegacy(root,"Large output"); + String text="x".repeat(1024*1024+8192); + try (var jobs=new RequestJobs(new ServerState(root),(r,in,out,err) -> { out.print(text); return 0; })) { + var response=done(jobs,jobs.submit(request("work","list"))); + assertThat(response.exitCode()).isZero(); assertThat(response.stdout().length()).isEqualTo(text.length()); + assertThat(jobs.get(response.id()).stdout().length()).isEqualTo(text.length()); + } + } +} diff --git a/src/test/java/net/intrepid/aiengineering/ServerStateTest.java b/src/test/java/net/intrepid/aiengineering/ServerStateTest.java new file mode 100644 index 0000000..35e6390 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/ServerStateTest.java @@ -0,0 +1,39 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.util.UUID; +import static org.assertj.core.api.Assertions.*; + +class ServerStateTest { + @TempDir Path root; + @Test void onlyOneOwnerAndDescriptorIsBoundToCanonicalProject() throws Exception { + Files.createDirectories(root.resolve(".ai-engineering")); + var state = new ServerState(root); state.initialize(); + var value = new ServerState.Descriptor(1, ServerIdentity.BUILD, root.toRealPath().toString(), + UUID.randomUUID().toString(), ProcessHandle.current().pid(), 12345, "a".repeat(64)); + state.publish(value); + assertThat(state.descriptor()).isEqualTo(value); + try (var owner = state.lock("owner.lock", 0)) { + assertThat(owner).isNotNull(); + assertThat(state.owned()).isTrue(); + } + assertThat(state.owned()).isFalse(); + state.removeDescriptor(UUID.randomUUID().toString()); + assertThat(state.descriptor()).isNotNull(); + state.removeDescriptor(value.instance()); assertThat(state.descriptor()).isNull(); + var other = new ServerState.Descriptor(1, ServerIdentity.BUILD, root.resolve("other").toString(), + value.instance(), value.pid(), value.port(), value.token()); + state.publish(other); + assertThatThrownBy(state::descriptor).hasMessageContaining("another project"); + } + @Test void localStateRejectsSymlinkComponents() throws Exception { + var outside = Files.createDirectory(root.resolve("outside")); + Files.createDirectory(root.resolve(".ai-engineering")); + Files.createSymbolicLink(root.resolve(".ai-engineering/.local"), outside); + assertThatThrownBy(() -> new ServerState(root)).hasMessageContaining("Symlink"); + assertThat(Files.list(outside).findAny()).isEmpty(); + } +} diff --git a/src/test/java/net/intrepid/aiengineering/SqliteDatabaseTest.java b/src/test/java/net/intrepid/aiengineering/SqliteDatabaseTest.java index 87acc20..0fa61e3 100644 --- a/src/test/java/net/intrepid/aiengineering/SqliteDatabaseTest.java +++ b/src/test/java/net/intrepid/aiengineering/SqliteDatabaseTest.java @@ -9,6 +9,30 @@ import static org.assertj.core.api.Assertions.*; class SqliteDatabaseTest { @TempDir Path root; + @Test void backendSelectionIsValidatedAndScopedToTheTransaction() throws Exception { + new net.intrepid.aiengineering.project.ProjectService().initializeSqlite(root,"Backend scope"); + Path manifest=root.resolve(".ai-engineering/protocol.json");String original=Files.readString(manifest); + try { + SqliteDatabase.read(root,connection->{ + assertThat(SqliteDatabase.active(root)).isTrue(); + Filespace.io(()->Files.writeString(manifest,original.replace("\"protocolVersion\": 4","\"protocolVersion\": 99"))); + // Related nested services keep the selected backend of this transaction. + assertThat(SqliteDatabase.active(root)).isTrue();return null; + }); + assertThatThrownBy(()->SqliteDatabase.active(root)).hasMessageContaining("protocol contract 4"); + } finally {Files.writeString(manifest,original);} + assertThat(SqliteDatabase.active(root)).isTrue(); + } + @Test void anOpenDatabaseNeverSelectsSqliteWithoutTheBootstrap() { + SqliteDatabase.initialize(root); + SqliteDatabase.read(root,connection->{assertThat(SqliteDatabase.active(root)).isFalse();return null;}); + } + @Test void unusedDatabasePathDoesNotAffectLegacyBackendSelection() throws Exception { + new net.intrepid.aiengineering.project.ProjectService().initializeLegacy(root,"Legacy selection"); + Path unrelated=Files.writeString(root.resolve("unrelated.txt"),"not a database"); + Files.createSymbolicLink(root.resolve(".ai-engineering/aie.db"),unrelated); + assertThat(SqliteDatabase.active(root)).isFalse(); + } private long count() { return SqliteDatabase.read(root, connection -> { diff --git a/src/test/java/net/intrepid/aiengineering/SqliteInvestigationTest.java b/src/test/java/net/intrepid/aiengineering/SqliteInvestigationTest.java index ae38ec9..3ffd972 100644 --- a/src/test/java/net/intrepid/aiengineering/SqliteInvestigationTest.java +++ b/src/test/java/net/intrepid/aiengineering/SqliteInvestigationTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.*; +@org.junit.jupiter.api.extension.ExtendWith(LocalServerCleanup.class) class SqliteInvestigationTest { @TempDir Path root; private final WorkService works = new WorkService(); diff --git a/src/test/java/net/intrepid/aiengineering/SseClientTest.java b/src/test/java/net/intrepid/aiengineering/SseClientTest.java new file mode 100644 index 0000000..8470d73 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/SseClientTest.java @@ -0,0 +1,80 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.project.ProjectService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.nio.file.Path; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.assertj.core.api.Assertions.*; + +class SseClientTest { + @TempDir Path root; + private static class Tracked implements ServerProtocol.Operations { + final RequestJobs jobs;final AtomicInteger submits=new AtomicInteger(),gets=new AtomicInteger(),streams=new AtomicInteger(),inputs=new AtomicInteger(),cancels=new AtomicInteger(); + final CountDownLatch resume; + Tracked(RequestJobs jobs,CountDownLatch resume){this.jobs=jobs;this.resume=resume;} + public ServerProtocol.View submit(ServerProtocol.Request r){submits.incrementAndGet();return jobs.submit(r);} + public ServerProtocol.View get(String id){gets.incrementAndGet();return jobs.get(id);} + public ServerProtocol.View input(ServerProtocol.Input input){inputs.incrementAndGet();return jobs.input(input);} + public ServerProtocol.View cancel(String id){cancels.incrementAndGet();return jobs.cancel(id);} + public int active(){return jobs.active();} + public ServerProtocol.EventSource events(String id){ + var source=jobs.events(id);int opened=streams.incrementAndGet(); + if(resume!=null && opened==2)resume.countDown(); + if(resume!=null && opened==1)return new ServerProtocol.EventSource(){ + int reads; + public ServerProtocol.Event next(String cursor,long timeout)throws InterruptedException{ + if(reads++>0)throw new IllegalStateException("Injected disconnect after snapshot"); + return source.next(cursor,timeout); + } + }; + return source; + } + public void close(){jobs.close();} + } + @Test void reconnectsByCursorWithoutPollingReexecutingOrDuplicatingOutput() throws Exception { + new ProjectService().initializeLegacy(root,"SSE client reconnect");var resume=new CountDownLatch(1);var executions=new AtomicInteger(); + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{ + executions.incrementAndGet();out.print("first café 😀\n");resume.await();out.print("tail\n");err.print("warning\n");return 0;}); + var operations=new Tracked(jobs,resume);var server=new ProjectServer(new ServerState(root),60000,operations); + var worker=Executors.newSingleThreadExecutor()) { + var stdout=new StringWriter();var stderr=new StringWriter(); + var client=new LocalClient(root,new StringReader(""),new PrintWriter(stdout),new PrintWriter(stderr),false); + var result=worker.submit(()->client.execute("work","list")); + try{assertThat(result.get(10,TimeUnit.SECONDS)).isZero();}finally{resume.countDown();result.cancel(true);} + assertThat(stdout).hasToString("first café 😀\ntail\n"); + assertThat(stderr.toString()).contains("warning","resuming request"); + assertThat(operations.streams).hasValue(2);assertThat(operations.gets).hasValue(0); + assertThat(operations.submits).hasValue(1);assertThat(executions).hasValue(1); + }finally{resume.countDown();} + } + @Test void sendsInteractiveInputOnceAndKeepsOutputStreamsSeparate() throws Exception { + new ProjectService().initializeLegacy(root,"SSE input"); + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{ + out.print("Choose café 😀: ");String line=new BufferedReader(in).readLine();out.println("got:"+line);err.print("remote warning\n");return 0;}); + var operations=new Tracked(jobs,null);var server=new ProjectServer(new ServerState(root),60000,operations)) { + var stdout=new StringWriter();var stderr=new StringWriter(); + int result=new LocalClient(root,new StringReader("sim 😀\n"),new PrintWriter(stdout),new PrintWriter(stderr),true) + .execute("survey","ask","WRK-0001","SVY-0001"); + assertThat(result).isZero();assertThat(stdout).hasToString("Choose café 😀: got:sim 😀\n"); + assertThat(stderr.toString()).contains("remote warning");assertThat(stdout.toString()).doesNotContain("warning"); + assertThat(operations.inputs).hasValue(1);assertThat(operations.gets).hasValue(0);assertThat(operations.streams).hasValue(1); + } + } + @Test void exhaustingReconnectBudgetLeavesJobRecoverableWithoutCancelOrReplay() throws Exception { + new ProjectService().initializeLegacy(root,"SSE retry limit");var finish=new CountDownLatch(1); + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{finish.await();return 0;}); + var operations=new Tracked(jobs,null){ + @Override public ServerProtocol.EventSource events(String id){streams.incrementAndGet();return (cursor,timeout)->{throw new IllegalStateException("Injected stream loss");};} + };var server=new ProjectServer(new ServerState(root),60000,operations)) { + var errors=new StringWriter(); + int code=new LocalClient(root,new StringReader(""),new PrintWriter(new StringWriter()),new PrintWriter(errors),false).execute("work","list"); + assertThat(code).isEqualTo(4);assertThat(errors.toString()).contains("reconnection limit"); + assertThat(operations.streams).hasValue(4);assertThat(operations.submits).hasValue(1); + assertThat(operations.cancels).hasValue(0);assertThat(jobs.active()).isEqualTo(1);finish.countDown(); + }finally{finish.countDown();} + } +} diff --git a/src/test/java/net/intrepid/aiengineering/SseHttpTest.java b/src/test/java/net/intrepid/aiengineering/SseHttpTest.java new file mode 100644 index 0000000..7e2f0d9 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/SseHttpTest.java @@ -0,0 +1,134 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import net.intrepid.aiengineering.project.ProjectService; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.assertj.core.api.Assertions.*; + +class SseHttpTest { + @TempDir Path root; + private ServerProtocol.Request request() throws IOException { + return new ServerProtocol.Request(UUID.randomUUID().toString(),root.toRealPath().toString(),root.toString(),List.of("work","list"),false); + } + private HttpURLConnection open(ServerState.Descriptor d,String id,String token,String cursor,String origin) throws IOException { + var connection=(HttpURLConnection)URI.create("http://127.0.0.1:"+d.port()+"/requests/"+id+"/events").toURL().openConnection(); + connection.setReadTimeout(5000); connection.setRequestProperty("Authorization","Bearer "+token); + connection.setRequestProperty("X-AIE-Instance",d.instance());connection.setRequestProperty("X-AIE-Protocol","1"); + if(cursor!=null)connection.setRequestProperty("Last-Event-ID",cursor); + if(origin!=null)connection.setRequestProperty("Origin",origin); + return connection; + } + private ServerProtocol.Event read(BufferedReader reader) throws IOException { + String line; + while((line=reader.readLine())!=null)if(line.startsWith("data: "))return ServerJson.decode(line.substring(6),ServerProtocol.Event.class); + throw new EOFException("No terminal SSE event"); + } + @Test void streamsBeforeCompletionWithDedicatedCapacityAndTerminalReceipt() throws Exception { + new ProjectService().initializeLegacy(root,"SSE");var finish=new CountDownLatch(1); + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{out.print("café 😀\n");finish.await();err.print("érr\n");return 7;}); + var server=new ProjectServer(new ServerState(root),60000,jobs)) { + var d=server.descriptor();var connection=new ServerConnection(d);var request=request(); + assertThat(connection.call("POST","/execute",request,ServerProtocol.View.class).state()).isEqualTo("RUNNING"); + var first=open(d,request.id(),d.token(),null,null);var second=open(d,request.id(),d.token(),null,null); + try { + var reader=new BufferedReader(new InputStreamReader(first.getInputStream(),StandardCharsets.UTF_8)); + var initial=read(reader);assertThat(initial.stdout()).isEqualTo("café 😀\n");assertThat(initial.terminal()).isFalse(); + assertThat(second.getResponseCode()).isEqualTo(200);assertThat(server.eventSubscribers()).isEqualTo(2); + var excess=open(d,request.id(),d.token(),null,null); + try {assertThat(excess.getResponseCode()).isEqualTo(400);}finally{excess.disconnect();} + assertThat(connection.health().active()).isEqualTo(1); + finish.countDown(); + var event=initial;StringBuilder errors=new StringBuilder(); + while(!event.terminal()){event=read(reader);errors.append(event.stderr());} + assertThat(errors).hasToString("érr\n");assertThat(event.exitCode()).isEqualTo(7); + assertThat(connection.call("GET","/requests/"+request.id(),null,ServerProtocol.View.class).state()).isEqualTo("COMPLETED"); + }finally{finish.countDown();first.disconnect();second.disconnect();} + } + } + @Test void enforcesAuthenticationOriginAndCursorBeforeOpeningStream() throws Exception { + new ProjectService().initializeLegacy(root,"SSE security"); + try(var jobs=new RequestJobs(new ServerState(root));var server=new ProjectServer(new ServerState(root),60000,jobs)) { + var d=server.descriptor();String id=UUID.randomUUID().toString(); + var forbidden=open(d,id,"0".repeat(64),null,null); + try{assertThat(forbidden.getResponseCode()).isEqualTo(403);}finally{forbidden.disconnect();} + // HttpURLConnection suppresses Origin; use a client that actually sends the browser header. + try(var browser=java.net.http.HttpClient.newHttpClient()) { + var request=java.net.http.HttpRequest.newBuilder(URI.create("http://127.0.0.1:"+d.port()+"/requests/"+id+"/events")) + .header("Authorization","Bearer "+d.token()).header("X-AIE-Instance",d.instance()) + .header("X-AIE-Protocol","1").header("Origin","https://example.invalid").GET().build(); + assertThat(browser.send(request,java.net.http.HttpResponse.BodyHandlers.ofString()).statusCode()).isEqualTo(403); + } + var invalid=open(d,id,d.token(),"bad-cursor",null); + try{assertThat(invalid.getResponseCode()).isEqualTo(400);}finally{invalid.disconnect();} + assertThat(server.eventSubscribers()).isZero(); + } + } + @Test void stalledSocketWriterIsDetachedWithoutCancellingItsJob() throws Exception { + new ProjectService().initializeLegacy(root,"Slow SSE");var emit=new CountDownLatch(1);var finish=new CountDownLatch(1); + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{emit.await();out.print("x".repeat(8*1024*1024));finish.await();return 0;}); + var server=new ProjectServer(new ServerState(root),60000,jobs);var socket=new Socket()) { + var d=server.descriptor();var request=request();var connection=new ServerConnection(d); + connection.call("POST","/execute",request,ServerProtocol.View.class); + socket.setReceiveBufferSize(1024);socket.connect(new InetSocketAddress("127.0.0.1",d.port()));socket.setSoTimeout(5000); + String headers="GET /requests/"+request.id()+"/events HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer "+d.token() + +"\r\nX-AIE-Instance: "+d.instance()+"\r\nX-AIE-Protocol: 1\r\n\r\n"; + socket.getOutputStream().write(headers.getBytes(StandardCharsets.US_ASCII));socket.getOutputStream().flush(); + var reader=new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));read(reader); + assertThat(server.eventSubscribers()).isEqualTo(1);emit.countDown(); + long deadline=System.nanoTime()+8_000_000_000L; + while(server.eventSubscribers()!=0 && System.nanoTime()get(id));} + } + @Test void globalSubscriberLimitDoesNotStarveHealthRequests() throws Exception { + try(var server=new ProjectServer(new ServerState(root),60000,new Pending(1))){ + var connection=new ServerConnection(server.descriptor());var open=new ArrayList(); + try{ + for(int i=0;iconnection.events(UUID.randomUUID().toString(),null)).hasMessageContaining("capacity"); + assertThat(connection.health().active()).isEqualTo(1); + }finally{for(var stream:open)stream.close();} + } + } + @Test void heartbeatOnlySubscriptionDoesNotPreventIdleShutdown() throws Exception { + try(var server=new ProjectServer(new ServerState(root),500,new Pending(0)); + var stream=new ServerConnection(server.descriptor()).events(UUID.randomUUID().toString(),null)){ + assertThat(stream.next().state()).isEqualTo("RUNNING"); + assertThat(server.await(4000)).isTrue();assertThat(new ServerState(root).descriptor()).isNull(); + } + } + @Test void completedReceiptCanBeSubscribedAfterRestartAndBeforeAnyLiveEvent() throws Exception { + new ProjectService().initializeLegacy(root,"Completed SSE");var request=request();ServerProtocol.View result; + try(var jobs=new RequestJobs(new ServerState(root),(r,in,out,err)->{out.print("complete café 😀");return 0;})){ + result=jobs.submit(request);long deadline=System.nanoTime()+5_000_000_000L; + while(!result.state().equals("COMPLETED") && System.nanoTime(){ + var reader=new BufferedReader(in);out.print("first: ");out.println("got1:"+reader.readLine()); + out.print("second: ");out.println("got2:"+reader.readLine());return 0; + }); + owner=state.lock("owner.lock",0);http=HttpServer.create(new InetSocketAddress("127.0.0.1",0),16);http.setExecutor(workers); + descriptor=new ServerState.Descriptor(1,ServerIdentity.BUILD,state.root.toString(),UUID.randomUUID().toString(), + ProcessHandle.current().pid(),http.getAddress().getPort(),"1".repeat(64)); + http.createContext("/",exchange->{ + boolean delegated=false; + try{ + String path=exchange.getRequestURI().getPath();Object result; + if(path.equals("/health"))result=new ServerProtocol.Health(1,descriptor.build(),descriptor.root(),descriptor.instance(),descriptor.pid(),false,jobs.active(),1800000,jobs.pending()); + else if(path.equals("/execute")){ + submits.incrementAndGet();result=jobs.submit(ServerJson.decode(new String(exchange.getRequestBody().readAllBytes(),StandardCharsets.UTF_8),ServerProtocol.Request.class)); + }else if(path.equals("/input")){ + var input=ServerJson.decode(new String(exchange.getRequestBody().readAllBytes(),StandardCharsets.UTF_8),ServerProtocol.Input.class); + boolean drop=inputPosts.incrementAndGet()==1; + if(drop && !dropAfterAcceptance)return; + result=jobs.input(input);acceptedInputs.incrementAndGet(); + if(drop)return; + }else if(path.endsWith("/events")){ + String id=path.substring(10,path.length()-7); + streams.open(exchange,id,exchange.getRequestHeaders().getFirst("Last-Event-ID"),jobs.events(id));delegated=true;return; + }else if(path.startsWith("/requests/")){gets.incrementAndGet();result=jobs.get(path.substring(10));} + else throw new IllegalArgumentException(path); + byte[] json=ServerJson.encode(result).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type","application/json");exchange.sendResponseHeaders(200,json.length);exchange.getResponseBody().write(json); + }finally{if(!delegated)exchange.close();} + });http.start();state.publish(descriptor); + } + public void close(){streams.close();http.stop(0);jobs.close();state.removeDescriptor(descriptor.instance());owner.close();workers.shutdownNow();} + } + private void recovers(boolean after)throws Exception{ + try(var endpoint=new Endpoint(root,after)){ + var stdout=new StringWriter();var stderr=new StringWriter(); + int code=new LocalClient(root,new StringReader("one 😀\ntwo é\n"),new PrintWriter(stdout),new PrintWriter(stderr),true) + .execute("survey","ask","WRK-0001","SVY-0001"); + assertThat(code).as(stderr.toString()).isZero(); + assertThat(stdout).hasToString("first: got1:one 😀\nsecond: got2:two é\n"); + assertThat(endpoint.submits).hasValue(1);assertThat(endpoint.acceptedInputs).hasValue(2); + assertThat(endpoint.gets).hasValue(1);assertThat(stderr.toString()).contains("Recovering request"); + assertThat(endpoint.inputPosts).hasValue(after?2:3); + } + } + @Test void lostInputBeforeAcceptanceReusesBufferedLineAndSequence()throws Exception{recovers(false);} + @Test void lostInputAfterAcceptanceDoesNotRepeatTheAnswer()throws Exception{recovers(true);} +} diff --git a/src/test/java/net/intrepid/aiengineering/SseReaderTest.java b/src/test/java/net/intrepid/aiengineering/SseReaderTest.java new file mode 100644 index 0000000..c93cce3 --- /dev/null +++ b/src/test/java/net/intrepid/aiengineering/SseReaderTest.java @@ -0,0 +1,39 @@ +package net.intrepid.aiengineering; + +import net.intrepid.aiengineering.localserver.*; +import org.junit.jupiter.api.Test; +import java.io.*; +import java.util.UUID; +import static org.assertj.core.api.Assertions.*; + +class SseReaderTest { + private final String id=UUID.randomUUID().toString(),cursor=UUID.randomUUID()+":1"; + private ServerProtocol.Event event(String kind,int offset,String text) { + return new ServerProtocol.Event(id,cursor,kind,offset,0,text,"","RUNNING",-1,0,false,false); + } + @Test void decodesCommentsMultilineDataCrLfAndUnicodeIncrementally() throws Exception { + String encoded=": heartbeat\n\n"+SseFrames.encode(event("snapshot",0,"café 😀\n")) + .replace("data: {","data: {\ndata: ").replace("\n","\r\n"); + try(var reader=new SseReader(new StringReader(encoded),id)) { + assertThat(reader.next()).isNull();assertThat(reader.next().stdout()).isEqualTo("café 😀\n"); + } + } + @Test void rejectsMismatchedIdentityAndIncompleteFramesBeforeDelivery() throws Exception { + String encoded=SseFrames.encode(event("snapshot",0,"hello")); + try(var reader=new SseReader(new StringReader(encoded.replace("event: snapshot","event: stdout")),id)) { + assertThatThrownBy(reader::next).hasMessageContaining("Invalid SSE"); + } + try(var reader=new SseReader(new StringReader(encoded.substring(0,encoded.length()-1)),id)) { + assertThatThrownBy(reader::next).isInstanceOf(EOFException.class); + } + } + @Test void verifiesSnapshotsAndOverlappingDeltasWithoutDuplicatingSurrogatePairs() { + var text=new StringWriter();var output=new RemoteOutput(new PrintWriter(text),new PrintWriter(new StringWriter())); + output.accept(event("snapshot",0,"A\ud83d")); + output.accept(event("stdout",1,"\ud83d\ude00B")); + output.accept(event("snapshot",0,"A😀B")); + assertThat(text).hasToString("A😀B"); + assertThatThrownBy(()->output.accept(event("stdout",99,"gap"))).hasMessageContaining("gap"); + assertThatThrownBy(()->output.accept(event("snapshot",0,"changed"))).hasMessageContaining("differs"); + } +} diff --git a/src/test/java/net/intrepid/aiengineering/WorkGuidanceTest.java b/src/test/java/net/intrepid/aiengineering/WorkGuidanceTest.java index abbe1b6..ae93972 100644 --- a/src/test/java/net/intrepid/aiengineering/WorkGuidanceTest.java +++ b/src/test/java/net/intrepid/aiengineering/WorkGuidanceTest.java @@ -11,6 +11,7 @@ import java.nio.file.*; import java.util.*; import static org.assertj.core.api.Assertions.*; +@org.junit.jupiter.api.extension.ExtendWith(LocalServerCleanup.class) class WorkGuidanceTest { @TempDir Path root; private String output; diff --git a/src/test/java/net/intrepid/aiengineering/agent/CliTransportTest.java b/src/test/java/net/intrepid/aiengineering/agent/CliTransportTest.java index 01e9771..c2c6ac3 100644 --- a/src/test/java/net/intrepid/aiengineering/agent/CliTransportTest.java +++ b/src/test/java/net/intrepid/aiengineering/agent/CliTransportTest.java @@ -12,6 +12,7 @@ import java.util.*; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.*; +@org.junit.jupiter.api.extension.ExtendWith(net.intrepid.aiengineering.LocalServerCleanup.class) class CliTransportTest { @TempDir Path root; private Path trace;