feat: bootstrap portable engineering protocol CLI

Implement milestones 0 and 1 with project and repository configuration, Work persistence, discussions, draft decisions, evidence integrity, and deterministic context exports.

Add Java 25, Spring Boot and Modulith, native distributions, CI workflows, protocol documentation, and the pinned SDKMAN GraalVM CE toolchain.

Validated with 20 passing tests and the macOS ARM64 native multi-repository continuity smoke.
This commit is contained in:
2026-11-11 16:14:22 +00:00
commit b91829270b
49 changed files with 2367 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
name: build
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
jvm:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
- uses: gradle/actions/setup-gradle@v4
- run: ./gradlew clean test bootJar --console=plain
- uses: actions/upload-artifact@v4
if: always()
with:
name: jvm-test-reports
path: build/reports/tests/test
native:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-24.04
platform: linux-x86_64
- os: macos-15
platform: macos-arm64
- os: windows-2025
platform: windows-x86_64
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: graalvm/setup-graalvm@v1
with:
version: '25.5'
distribution: graalvm-community
github-token: ${{ secrets.GITHUB_TOKEN }}
- uses: gradle/actions/setup-gradle@v4
- name: Build native archive
shell: bash
run: ./gradlew nativeDistZip -PtargetPlatform=${{ matrix.platform }} --console=plain
- name: Native continuity smoke
shell: bash
run: |
native_binary="$PWD/build/native/nativeCompile/ai-engineering"
if [[ "$RUNNER_OS" == Windows ]]; then native_binary="${native_binary}.exe"; fi
bash scripts/native-smoke.sh "$native_binary"
- uses: actions/upload-artifact@v4
with:
name: ai-engineering-${{ matrix.platform }}
path: build/distributions/*.zip
# GraalVM 25 no longer provides macOS x86_64. See docs/roadmap.md.
+5
View File
@@ -0,0 +1,5 @@
.gradle/
build/
.idea/
*.iml
.DS_Store
+1
View File
@@ -0,0 +1 @@
java=25.5.5.0+3-graalce
+128
View File
@@ -0,0 +1,128 @@
# ai-engineering
An open, agent-agnostic engineering protocol and CLI. Works belong to an engineering
project spanning independent repositories. Canonical files preserve goals, discussion,
draft decisions and evidence so another person or agent can continue without chat history.
Milestones 0 and 1 are implemented. The application runs locally in non-web mode;
it needs no model API, database or running service.
## Build and run
Build requirements: JDK 25, Git (for repository inspection and integration fixtures),
and internet access for the first dependency download. The Gradle Wrapper is included.
The recommended local toolchain is GraalVM Community Edition, pinned in `.sdkmanrc`.
With SDKMAN installed, activate it from the project root:
```sh
sdk env install # only needed if the pinned JDK is not installed
sdk env
export GRAALVM_HOME="$JAVA_HOME"
java --version
native-image --version
```
SDKMAN candidate `25.5.5.0+3-graalce` provides GraalVM CE 25.5.5.0.3 based on
JDK 25.0.5.0.3. The Java language/bytecode target remains 25. SDKMAN is optional;
setting `JAVA_HOME` and `GRAALVM_HOME` to an equivalent GraalVM installation also works.
```sh
./gradlew clean test
./gradlew bootJar
java -jar build/libs/ai-engineering-0.1.0.jar --help
java -jar build/libs/ai-engineering-0.1.0.jar --version
```
Pinned stack: Java target 25, Spring Boot 4.0.9, Spring Modulith 2.0.9,
Gradle 9.3.1, Picocli 4.7.7, Native Build Tools 0.11.5, JUnit 5.13.4.
Jackson YAML/JSON and AssertJ versions come from the pinned Spring Boot BOM.
Compatibility sources and rationale are in [architecture](docs/architecture.md).
## Native installation and packaging
A native distribution contains `ai-engineering` (`ai-engineering.exe` on Windows).
Extract the platform archive and put that executable on `PATH`. Running it requires
no JVM. Git must be on `PATH` for commands that inspect registered repositories.
There are no published release downloads yet; packaging tasks create local archives.
Building requires GraalVM for **JDK 25**, Native Image and the host C/C++ toolchain:
Xcode Command Line Tools on macOS, GCC and development libraries on Linux, or the
Visual Studio C++ build tools on Windows. Set `JAVA_HOME` and `GRAALVM_HOME` to the
GraalVM JDK home (`Contents/Home` on macOS).
```sh
./gradlew nativeCompile
./build/native/nativeCompile/ai-engineering --help
./gradlew nativeDistZip nativeDistTar -PtargetPlatform=macos-arm64
bash scripts/native-smoke.sh "$PWD/build/native/nativeCompile/ai-engineering"
```
Archives are written to `build/distributions/ai-engineering-0.1.0-<platform>.*`.
Build each binary on its target OS/architecture; Native Image is not a general cross
compiler. CI defines Linux x86_64, macOS ARM64 and Windows x86_64 native builds.
macOS x86_64 remains a target with an upstream toolchain availability limitation:
GraalVM 25 dropped that port; see [roadmap](docs/roadmap.md). Local verification
results, including which native binaries were actually tested, are in [experiments](docs/experiments.md).
## Two-repository example
From an external project directory with existing `runtime/` and `studio/` Git
repositories, run:
```sh
ai-engineering init --name "Prometeu"
ai-engineering repo add runtime --path runtime --language rust
ai-engineering repo add studio --path studio --language java
ai-engineering repo list --format json
ai-engineering work create "Improve scene editor" \
--repo runtime --repo studio \
--goal "Evaluate portable scene rendering" \
--constraint "No external service" \
--acceptance "A fresh execution reconstructs the context"
ai-engineering discussion add WRK-0001 --kind QUESTION \
--text "Should we use layered Canvas?"
ai-engineering discussion add WRK-0001 --kind RESPONSE --responds-to DSC-0001 \
--text "Run a rendering experiment first"
ai-engineering artifact add WRK-0001 --file result.txt \
--purpose "Rendering measurements" --origin "manual experiment"
ai-engineering decision draft WRK-0001 --title "Evaluate layered Canvas" \
--context "Scene editor rendering" --approach "Prototype layers" \
--rationale "Measure before committing" --evidence ART-0001
ai-engineering work context WRK-0001 --format markdown
ai-engineering work context WRK-0001 --format json
ai-engineering project validate
```
The CLI never initializes or modifies Git repositories. To register an existing
submodule use `--type git-submodule`; the default is `linked-git`. Repositories are
read-only unless registration explicitly includes `--allow-edit`. This is policy
metadata; it does not replace an operating-system sandbox. No source edits or
configured validation commands are executed in these milestones.
`--project /path/to/project` works before or after subcommands. Otherwise discovery
searches upward, including when invoked inside a nested source directory. Work
IDs are stable (`WRK-0001`); child IDs are scoped to their Work. New discussions can
be grouped with `--discussion <name>`. History remains append-only. `work status
WRK-0001 ACTIVE` changes lifecycle status; all initial statuses are reversible.
Every command provides `--help`; inspection commands support `--format json`.
Exit codes: **0** success, **1** unexpected I/O/runtime failure, **2** invalid input
or unsafe path, **3** missing project/resource, **4** structural validation failure.
Validation commands return 4 with diagnostics even when the underlying issue is a
missing referenced resource or unsafe persisted path.
## Architecture and protocol
One Gradle project, one Spring Boot application, eight verified Modulith modules:
project, work, discussion, decision, artifact, verification, CLI and shared filesystem
infrastructure. Domain state is immutable Java records; persistence uses versioned
YAML and Markdown front matter. Files remain understandable without this CLI.
- [Architecture and reuse decisions](docs/architecture.md)
- [Protocol schema and persistence guarantees](docs/protocol.md)
- [Roadmap and acceptance criteria](docs/roadmap.md)
- [Experiments and actual validation results](docs/experiments.md)
No Agenda, Lesson, autonomous OODA engine, agent orchestration or concrete AI adapter
is part of this implementation.
+71
View File
@@ -0,0 +1,71 @@
import org.gradle.api.tasks.bundling.Compression
plugins {
java
id("org.springframework.boot") version "4.0.9"
id("org.graalvm.buildtools.native") version "0.11.5"
}
group = "net.intrepid"
version = "0.1.0"
java { toolchain { languageVersion = JavaLanguageVersion.of(25) } }
repositories { mavenCentral() }
dependencies {
implementation(platform("org.springframework.boot:spring-boot-dependencies:4.0.9"))
implementation(platform("org.springframework.modulith:spring-modulith-bom:2.0.9"))
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.modulith:spring-modulith-starter-core")
implementation("info.picocli:picocli:4.7.7")
annotationProcessor("info.picocli:picocli-codegen:4.7.7")
implementation("tools.jackson.dataformat:jackson-dataformat-yaml")
testImplementation("org.springframework.modulith:spring-modulith-starter-test") {
exclude(group = "org.junit.jupiter")
exclude(group = "org.junit.platform")
}
testImplementation(enforcedPlatform("org.junit:junit-bom:5.13.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.assertj:assertj-core")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
options.compilerArgs.add("-parameters")
}
tasks.test {
useJUnitPlatform()
dependsOn(tasks.bootJar)
systemProperty("cli.jar", tasks.bootJar.get().archiveFile.get().asFile.absolutePath)
}
springBoot { mainClass = "net.intrepid.aiengineering.AiEngineeringApplication" }
graalvmNative {
binaries.named("main") {
imageName = "ai-engineering"
buildArgs.addAll("--no-fallback", "-O1")
}
}
val platformName = providers.gradleProperty("targetPlatform").orElse(
"${System.getProperty("os.name").lowercase().replace(" ", "-")}-${System.getProperty("os.arch")}")
tasks.register<Zip>("nativeDistZip") {
dependsOn("nativeCompile")
archiveBaseName = "ai-engineering"
archiveClassifier = platformName
destinationDirectory = layout.buildDirectory.dir("distributions")
from(layout.buildDirectory.dir("native/nativeCompile")) {
include("ai-engineering", "ai-engineering.exe")
filePermissions { unix("rwxr-xr-x") }
}
from("README.md")
from("docs") { into("docs") }
}
tasks.register<Tar>("nativeDistTar") {
dependsOn("nativeCompile")
archiveBaseName = "ai-engineering"
archiveClassifier = platformName
archiveExtension = "tar.gz"
compression = Compression.GZIP
destinationDirectory = layout.buildDirectory.dir("distributions")
from(layout.buildDirectory.dir("native/nativeCompile")) { include("ai-engineering"); filePermissions { unix("rwxr-xr-x") } }
from("README.md")
from("docs") { into("docs") }
}
+100
View File
@@ -0,0 +1,100 @@
# Architecture
## Technology selection
The project deliberately stays on a compatible maintenance pair: **Spring Boot
4.0.9 and Spring Modulith 2.0.9**. The published Modulith 2.0.9 POM declares
Boot autoconfigure 4.0.9. Java compilation and bytecode target are both **25**,
without preview features. Gradle **9.3.1** supports running on Java 25; its Wrapper
distribution is pinned with SHA-256 verification.
The local development JDK is pinned through `.sdkmanrc` to SDKMAN candidate
`25.5.5.0+3-graalce` (GraalVM CE 25.5.5.0.3, OpenJDK 25.0.5.0.3). This
[GraalVM innovation release](https://www.graalvm.org/release-notes/25.5/) still uses
Java 25. It provides both JVM and Native Image tooling without changing compilation
target or application dependencies. Use `sdk env` for project-scoped activation;
the Gradle Wrapper remains responsible for the Gradle version.
Primary compatibility references checked during implementation:
- [Spring Boot 4.0 requirements](https://docs.spring.io/spring-boot/4.0/system-requirements.html): Java 25, Gradle 9 and GraalVM 25 are supported; Native Build Tools 0.11.5 is the documented version.
- [Published Modulith 2.0.9 dependencies](https://repo.maven.apache.org/maven2/org/springframework/modulith/spring-modulith-core/2.0.9/spring-modulith-core-2.0.9.pom): Boot 4.0.9 dependency.
- [Gradle Java compatibility](https://docs.gradle.org/9.3.1/userguide/compatibility.html): Java 25 support starts at Gradle 9.1.
- [Spring AOT Gradle integration](https://docs.spring.io/spring-boot/4.0/gradle-plugin/aot.html).
- [Picocli native configuration](https://picocli.info/#_graalvm_native_images): annotation-processor-generated reflection metadata.
- [GraalVM 25 release notes](https://www.graalvm.org/release-notes/JDK_25/): macOS x86_64 support was removed.
Picocli **4.7.7** handles argument validation, help and dispatch. Jackson 3 YAML/JSON
comes from Boot's BOM. JUnit is explicitly pinned to **5.13.4** because the requested
test baseline is JUnit 5; the Boot BOM otherwise selects a newer major generation.
AssertJ and Modulith/ArchUnit verify behavior and dependencies. There is no Spring AI,
Embabel, web starter, persistence server or workflow framework.
## Module boundaries
All packages below are under `net.intrepid.aiengineering`. A module's base package is
its explicit public API; implementation-only Git adapters live in `project.internal`.
`package-info.java` declares allowed dependencies. `ArchitectureTest` calls
`ApplicationModules.verify()` to enforce cycles, visibility and dependency rules.
| Module | Owns | May depend on |
|---|---|---|
| filesystem | Protocol codecs, safe paths, atomic file writes, locks, errors | none |
| project | Configuration, discovery, repository policy, read-only Git adapter | filesystem |
| work | Work identity, lifecycle, repository snapshots and reference manifest | project, filesystem |
| discussion | Append-only refinement entries and thread grouping | work, filesystem |
| decision | Draft DEC records | work, filesystem |
| artifact | Small evidence payloads and integrity metadata | work, filesystem |
| verification | Structural conformance and portable context assembly | all protocol modules |
| cli | Picocli commands, formats, exit codes | all APIs above |
Spring owns the process lifecycle and CLI bean, and supplies AOT processing. Protocol
services are ordinary Java classes with explicit path arguments and no retained Work
cache. This keeps direct tests and fresh instances simple. Infrastructure dependencies
remain inside services, outside immutable domain records. The small `GitAdapter` port
is internal to Project and can be replaced without changing Work contracts.
Context assembly belongs to Verification because it combines independently persisted
modules and refuses to export structurally inconsistent state. Work does not depend
on Discussion, Decision or Artifact, avoiding cycles. It owns stable references only.
## Persistence and native execution
Writers take an OS file lock per project. Complete UTF-8 files are written to a sibling
temporary file, forced to disk and published atomically. New files use a hard link
to avoid overwriting an existing destination. Existing files use atomic replacement;
unsupported filesystems fail instead of quietly falling back to partial writes.
New Works, projects and artifact payload bundles are staged before directory rename.
See the protocol document for crash limits and recovery.
Jackson parses explicit records, rejects unknown fields, duplicate YAML keys and
unsupported schema versions. Native hints register those records; Picocli's annotation
processor provides command reflection metadata. The Spring AOT tasks are wired by the
native build plugin. No application arguments are passed through Spring's property
parser. The entry point explicitly chooses non-web mode and closes its context.
## Earlier framework review and migration
Both implementations were inspected read-only:
- The user-identified Python repository at
`/Users/niltonconstantino/personal/workspace.personal/intrepid/discussion-framework`:
README, model/locking/index persistence and structural validation.
- The sibling Java `discussion-framework`: `DiscussionOrchestrator`,
`WorkflowValidator`, `WorkPacket`, `ArtifactDocumentParser` and
`FilesystemDiscussionRepository` concepts and implementations.
Reused concepts: deterministic context as the handoff surface, stable IDs, explicit
references, file locks, atomic replacement, duplicate/reference checks and separating
content from mechanical CLI state management. No Python code or dependency was copied.
The old generic Markdown inference was replaced by typed, versioned front matter;
semantic sections are explicit and cannot silently disappear from context parsing.
No legacy HTTP adapter, NDJSON global index, accepted-agenda gate, automatic housekeeping
deletion or Lesson model was retained. Work is the project-scoped aggregate; Discussion
is refinement within a Work. Source repositories were not changed.
There is no automated legacy importer in Milestone 1. A future migration should create
one Work per coherent agenda, retain original discussion/decision text with origin
references, and verify identifiers and links before publication. Legacy Lessons should
be reviewed for integration into canonical docs, not recreated as a required entity.
+149
View File
@@ -0,0 +1,149 @@
# Initial experiments
Execution host: macOS ARM64, 2026-11-11. JVM: Amazon Corretto 25.0.4+7.
Native toolchain: Oracle GraalVM for JDK 25.0.4+7.1 and Apple C compiler.
Resolved Jackson YAML/Databind: 3.1.7 (Boot BOM). No Python, Node, model API,
database or external runtime service was used.
## H1 — One non-web modular application is enough
Observation: the packaged Spring Boot application prints Picocli help/version and
terminates. Automated process tests enforce a 30-second termination limit. There
are no web/server dependencies. Modulith verifies eight modules and their declared
dependency graph.
Result: verified by `ArchitectureTest`, CLI smoke tests and independent JVM processes.
Spring handles process lifecycle and AOT; the portable protocol stays plain Java.
## H2 — Files alone preserve meaningful engineering state
The main integration fixture initializes an engineering project with two independent
Git repositories (`runtime`, `studio`), creates a Work referencing both, supplies goal,
constraints and acceptance criteria, appends a question/conclusion, persists a draft
DEC and attaches evidence. A fresh CLI instance invoked from `studio/src/editor`
reconstructs exactly the same exported context.
`ProcessContinuityTest` repeats the scenario through separate `java -jar` processes.
Each source repository contains a real fixture commit. The fresh context includes
both revision snapshots, author, discussion, DRAFT status and evidence SHA-256. JSON
exports from independent processes compare byte-for-byte. Project validation succeeds.
Result: verified without shared application memory or conversation history. The native
smoke script reproduces the same scenario with a separate native process per command.
## H3 — Structural safety and integrity are testable without a model
Verified cases: multiple Works, separate artifact workspaces, missing repositories,
unknown configuration fields/schema, malformed YAML and duplicate YAML keys,
traversal and symlink attempts, malformed/missing/duplicate Work identifiers,
missing decision files and evidence payloads, orphan records, required directories,
SHA-256 corruption, explicit question replies, reversible status, default read-only
access, immutable models, atomic no-overwrite writes and persistent ID reservations.
A real submodule fixture additionally verifies registration without rewriting
`.gitmodules`. It initially exposed a path equality bug between macOS `/var` and
`/private/var`. Comparing both real paths fixed it. A numeric-enum negative fixture
initially failed to alter Jackson's quoted YAML; the corrected fixture now verifies
that ordinal lifecycle values are rejected.
Result: final clean build has **20 tests, 0 failures, 0 errors, 0 skipped**.
The first test-first run intentionally failed because implementation classes did not
exist. Intermediate compilation caught interruption handling and a Jackson 2 feature
constant moved to Jackson 3's `EnumFeature`; both were corrected. These failures are
resolved in the final tested source.
## Commands and evidence
```sh
./gradlew clean test bootJar --console=plain
./gradlew dependencies --configuration runtimeClasspath --console=plain
JAVA_HOME=<graalvm25-home> GRAALVM_HOME=<graalvm25-home> \
./gradlew nativeCompile nativeDistZip nativeDistTar \
-PtargetPlatform=macos-arm64 --console=plain
```
The clean test/JAR build passed. Generated test reports are under
`build/reports/tests/test`; raw JUnit XML is under `build/test-results/test`.
Runtime dependency inspection confirmed the pinned Spring pair and Jackson 3.1.7.
An initial Native Image compilation succeeded, but only the final rebuilt binary's
execution results count as native functionality verification.
Native result: **compiled and executed successfully on macOS ARM64**. The initial
verified Native Image build completed in approximately 1m 13s (Gradle invocation:
1m 23s). `ai-engineering` is a Mach-O ARM64 executable. ZIP and tar.gz archives were
generated with executable permissions and inspected.
The native continuity smoke passed with no JDK on the configured execution path:
```sh
JAVA_HOME=/nonexistent PATH=/usr/bin:/bin:/usr/sbin:/sbin AIE_KEEP_FIXTURE=1 \
bash scripts/native-smoke.sh "$PWD/build/native/nativeCompile/ai-engineering"
```
Observed output: `Native multi-repository continuity smoke passed.` Every CLI command
in the script starts a separate process. Help/version, exit code 2 for invalid input,
both repository registrations, Work creation, discussion, evidence, DEC draft,
nested discovery, JSON byte equality, Markdown export and final structural validation
all succeeded. The engineering fixture root had no `.git` directory.
The retained local demonstration fixture is at
`/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/ai-engineering-smoke.ziQUkw`.
Inspect `.ai-engineering/works/WRK-0001-improve-scene-editor/`, `before.json`,
`after.json`, `context.md` and `validation.json` there. The JSON validation report
contains `valid: true` and an empty issue list. Temporary fixtures are not required
for future use; the committed script can recreate the experiment.
Nonblocking Native Image build warnings: Picocli's generated proxy metadata uses a
deprecated configuration resource option; SLF4J reports no provider during image
analysis. Neither prevented compilation or the full native execution scenario.
An earlier exploratory native invocation was terminated with exit 137 during a clean
rebuild; it was not treated as a functional pass. The final rebuilt binary passed the
full smoke scenario above.
## H4 — SDKMAN GraalVM Community toolchain
The local project JDK is now pinned in `.sdkmanrc` to SDKMAN candidate
`25.5.5.0+3-graalce`. Direct inspection identifies GraalVM Community Edition
25.5.5.0.3+1.1, based on OpenJDK 25.0.5.0.3, with Native Image included. Gradle
9.3.1 recognizes it as both launcher and daemon JVM. A clean Java/AOT/JAR build
and all **20 tests** passed again using this installation. The language and bytecode
target remain Java 25. CI native builds select the Community 25.5 series; CI itself
has not been executed locally.
Native compilation with Native Build Tools 0.11.5 also succeeded (image generation
approximately 1m 8s; complete clean test/JAR/native invocation 1m 40s). The full native
continuity smoke passed with the CE-built executable, including project validation
and byte-identical context exports across processes. An isolated copy containing only
the executable passed the same scenario with both `JAVA_HOME` and `GRAALVM_HOME` set
to nonexistent paths and no JDK on the configured PATH. Native Image also emitted
optional desktop libraries beside the build output; the implemented CLI commands
were verified without those libraries present beside the isolated executable.
The compiler reports nonblocking deprecation warnings for `--no-fallback`,
`FallbackThreshold` and Picocli's proxy configuration. No application dependency or
native plugin upgrade was needed for the tested functionality.
Reproduction after `sdk env`:
```sh
export GRAALVM_HOME="$JAVA_HOME"
./gradlew clean test bootJar nativeCompile --console=plain
JAVA_HOME=/nonexistent GRAALVM_HOME=/nonexistent PATH=/usr/bin:/bin:/usr/sbin:/sbin \
bash scripts/native-smoke.sh "$PWD/build/native/nativeCompile/ai-engineering"
```
## Limits and next experiment
CI workflows are provided but have not been executed from this local workspace.
Linux x86_64 and Windows x86_64 binaries are not locally verified. GraalVM 25 removed
macOS x86_64 support, so that release target has no claimed native artifact.
Filesystem atomicity is per file/directory publication, not a transaction across the
child record and parent manifest. Orphans after interruption are detected, not
automatically repaired. Manual concurrent editors and adversarial path replacement
require external coordination/sandboxing. Artifact attachment is limited to small
files, and no full provenance/environment capture or agent intelligence is implemented.
Next recommended experiment: define a deterministic AgentAdapter test contract and
demonstrate two fake adapters continuing the same Work. Keep that work in Milestone 2;
no adapter implementation is included here.
+167
View File
@@ -0,0 +1,167 @@
# Portable engineering protocol — schema 1
## Project root and configuration
The engineering root is the parent of `.ai-engineering`. Repository paths resolve
against that root, independently of the CLI's current directory. Discovery searches
upward or accepts an explicit `--project` root (or `.ai-engineering` directory).
```yaml
schemaVersion: 1
project:
id: prometeu
name: Prometeu
repositories:
- id: runtime
path: runtime
type: linked-git
language: rust
access:
read: true
edit: false
validationCommands: []
```
IDs use lowercase ASCII letters, digits and hyphens, beginning with a letter.
Repository types are `linked-git` and `git-submodule`. Omitted `access` defaults to
`read: true, edit: false`. If `access` is supplied its booleans are explicit; edit
requires read. Language is optional. `validationCommands` is optional metadata,
never executable through this release. Unknown fields and schema versions fail validation.
Absolute repository paths, `..` components, backslashes and symlinks beneath the root
are rejected, including links that point inside the root. This stricter initial rule
avoids ambiguous link policies. Repositories cannot be the engineering root or live
inside `.ai-engineering`. Git inspection verifies an independent repository top-level;
submodule registration additionally verifies its superproject. Paths must exist.
No submodules are automatically created, moved or updated.
Policy controls protocol intent, not OS security. Concurrent malicious filesystem
replacement is outside this CLI's sandbox guarantee; use OS isolation for untrusted
processes. The adapter clears inherited `GIT_*` variables and disables optional Git locks.
## Work and files
```text
.ai-engineering/
ai-engineering.yaml
.gitignore
.local/write.lock # ignored, no semantic state
contracts/ # reserved for project contracts
works/
.sequence.yaml # canonical high-water mark; commit this
WRK-0001-improve-scene-editor/
work.md
discussions/DSC-0001.md
decisions/DEC-0001.md
artifacts/
references/
experiments/
evidence/ART-0001/
artifact.yaml
payload
outputs/
runs/ # ignored temporary execution outputs
```
`work.md`, discussion and decision files contain YAML front matter, delimited by
`---`. All semantic content lives in the front matter in this version; trailing
Markdown is reserved for noncanonical notes and is not exported. YAML multiline strings
remain human-readable. Edit the typed fields to update canonical content. There is no
Java object serialization and no dependency on conversation state.
Work fields: `schemaVersion`, `id`, `title`, `description`, `goal`, `motivation`,
`constraints[]`, `acceptanceCriteria[]`, `status`, `createdAt`, `updatedAt`, `author`,
`repositories[]`, `discussions[]`, `decisions[]`, `artifacts[]`. Each repository snapshot
records `repositoryId`, relative `path`, exact `head` commit and `dirty`. An empty
repository records `UNBORN`, not an invented commit. Snapshots are taken at Work
creation and remain stable; they are not claims about later experiments.
Work IDs are project-wide, monotonic `WRK-` numbers with at least four digits. A
persisted sequence reserves identity before publishing a Work; crashes may leave gaps.
Do not remove or rewind the sequence. Discussion/decision/artifact IDs are **Work-local**;
their full identity is `(project, Work ID, child ID)`. Work reference arrays determine
history order. Directory names are a convenience; ID stability does not depend on title.
Duplicate Work IDs and directory/record mismatches fail validation.
Initial statuses: OPEN, ACTIVE, BLOCKED, COMPLETED, CANCELLED. `work status` permits
reorientation without irreversible lifecycle gates. Completion currently records intent;
it does not prove acceptance criteria. Conformance automation belongs to Milestone 5.
## Discussion and draft decisions
Each discussion entry has `schemaVersion`, `id`, `workId`, `discussionId` (thread name),
`kind`, `author`, `createdAt`, optional `respondsTo`, and `text`. Multiple threads can
coexist. Kinds: NOTE, QUESTION, RESPONSE, SUGGESTION, ASSUMPTION, HYPOTHESIS,
INVESTIGATION, ALTERNATIVE, ISSUE, CONCLUSION. Entries are appended, not rewritten.
Text is supplied by a human or external agent; the CLI never fabricates conclusions.
A response must refer to an earlier entry in the same Work. Outstanding questions
include QUESTION and ISSUE entries without an explicit RESPONSE or CONCLUSION pointing
to them. This mechanical definition does not infer agreement or approval from prose.
Draft DEC fields: `schemaVersion`, `id`, `workId`, `title`, `context`, `approach`,
`alternatives[]`, `rationale`, `risks[]`, `acceptanceCriteria[]`, `approvalStatus`,
`author`, `createdAt`, `evidence[]`. Only DRAFT is accepted in this release. Empty
refinement fields are legal in drafts. The CLI initially supplies context, approach,
rationale and evidence; remaining fields can be refined in the canonical YAML.
No approval, supersession or autonomous operational decision is implemented.
## Evidence and integrity
`artifact add` copies one regular file up to 1 MiB. Its manifest records schema, ID,
Work ID, origin, purpose, Work-relative payload path, SHA-256, byte size, author and UTC
creation time. The origin defaults to the source basename; use `--origin` for a useful
portable provenance reference. Payload bytes are exact. The fixed `payload` filename
avoids filename ambiguity; origin preserves the supplied source identity.
Validation checks required directories, IDs, schemas, repository references, child
ownership, missing records, orphan records and payload integrity. Evidence paths stay
inside the Work. Large resources should remain in their canonical location and be
described in discussion/reference files, rather than copied into this workspace.
`artifacts/outputs` is versionable for deliberately retained outputs; use ignored `runs/`
for large temporary results. No command creates large output files by default.
## Context and continuity
`work context --format markdown|json` loads only canonical project/Work files. It
includes all Work fields (metadata separately in Markdown), stored source revisions,
ordered discussion history/conclusions, explicit draft decisions, unresolved questions
and complete artifact references with integrity metadata. JSON has top-level
`schemaVersion`, `work`, `discussionHistory`, `decisions`, `outstandingQuestions`,
`artifacts`. It does not embed arbitrary evidence payloads.
No export timestamp, current absolute path or live Git state is injected. Unchanged
files yield byte-identical output across new instances and processes. Export rejects
broken references or integrity failures. It requires neither a model nor live Git
inspection; `project validate` separately verifies live repositories.
## Write guarantees and recovery
Protocol mutations hold `.local/write.lock`, an OS lock released automatically at
process exit. Individual files publish atomically; create operations reject overwrites.
New project/Work/artifact directories are staged and renamed. Work sequence reservation
precedes directory publication to avoid identity reuse after interruption.
A child file/bundle is published before its reference is atomically added to `work.md`.
The filesystem is not a multi-file transactional database: interruption in that window
can leave an orphan, which validation reports. Inspect its metadata and either add its
ID to the Work reference array or remove it after review. Hidden `.tmp` directories are
incomplete staging outputs, ignored by readers; inspect and clean them manually after
an interrupted write. Concurrent manual editors do not honor the CLI lock. Directory
entry durability under sudden power loss depends on the host filesystem.
## Future contracts (design only)
- AgentAdapter: accept versioned context and return proposed questions, suggestions,
assumptions or draft content with provenance. The caller decides what to persist;
no provider or orchestration dependency is part of schema 1.
- OODA iteration: identify Work and prior observations, orientation, operational
choices and attempts. Phases can repeat or be skipped; no four-stage workflow gate.
- Attempt: stable identity, hypothesis, input references, exact repository revisions,
granted permissions, invocation/environment, observations, outputs, result and
evidence references. Evidence and interpretation remain distinguishable.
- Coordinated execution: independent per-repository worktrees and commit records,
integrated validation, explicit authority for destructive actions, pushes and merges.
No claim of atomic commits across repositories.
- Conformance: evaluate explicit criteria against evidence and canonical code/spec/test
updates. No required Lesson artifact. Later schema changes require explicit migration.
+63
View File
@@ -0,0 +1,63 @@
# Roadmap
## Milestone 0 — Bootstrap
Implemented: Java 25, Spring Boot 4, non-web Picocli entry point, one Gradle Kotlin DSL
project with Wrapper, Modulith boundaries, help/version smoke tests, Spring AOT,
Native Image configuration and native archive tasks. Acceptance: clean tests and JAR
build pass, CLI terminates and errors are meaningful. Native results are tracked in
the experiment log, separately from configuration claims.
## Milestone 1 — Portable engineering protocol
Implemented: project discovery/init, schema 1 configuration, linked Git/submodule
registry and default read-only policy, stable Work IDs, local artifact workspaces,
discussion history, draft DECs, evidence integrity, structural validation and stable
Markdown/JSON context. Temporary-fixture tests cover continuity, independent Works,
multiple repositories and malformed/missing/unsafe state.
Acceptance demonstration: initialize a project with two independent Git repositories,
create a Work referencing both, append discussion, persist a draft decision and
evidence, export context, then reconstruct the same context in independent processes
using only files. No framework state or model history may be required.
Platform release targets: Linux x86_64, macOS ARM64, macOS x86_64 and Windows x86_64.
The workflow builds the three available GraalVM 25 platforms. **macOS x86_64 is blocked
by upstream GraalVM 25 support removal**, documented in the
[official release notes](https://www.graalvm.org/release-notes/JDK_25/).
Do not substitute an older Java target or label an ARM binary as Intel. A future
distribution experiment must identify and validate a maintained compatible toolchain
before enabling that native release target. CI configuration is not evidence that CI
has run; see actual local results in experiments.
## Milestone 2 — Intelligent Discussion (design only)
Introduce a replaceable AgentAdapter using the portable context contract. Begin with
deterministic fakes and persist proposed questions/alternatives/assumptions as explicit
entries. Acceptance: two different adapters continue the same Work without private
history; humans retain authority over formal commitments. No model integration yet.
Recommended next experiment: two deterministic adapters read the same schema 1 context,
one proposes a clarification and another continues from its persisted response. First
confirm the context contract is sufficient; then choose provider integrations.
## Milestone 3 — Adaptive OODA (design only)
Add observations, orientation, operational decisions and Attempts using the conceptual
contracts in protocol.md. Acceptance: experiment evidence changes the next action;
history prevents repeating an invalidated attempt without a stated new hypothesis.
No rigid Observe→Orient→Decide→Act pipeline or autonomous engine is implemented now.
## Milestone 4 — Coordinated repositories (design only)
Add per-Work permissions, independent worktrees, exact source revisions, coordinated
validation and separate commit outcomes. Acceptance: partial success in one repository
remains visible; destructive actions, push and merge require explicit authorization.
Never assume atomic commit across repositories.
## Milestone 5 — Knowledge integration and conformance (design only)
Check acceptance criteria against evidence; identify impacted canonical specs, tests,
code and documentation; expose conformance checks to agents and CI. Acceptance: a Work
can demonstrate its outcome and preserve actionable knowledge without a mandatory
Lesson model or redundant documentation trail.
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
distributionSha256Sum=b266d5ff6b90eada6dc3b20cb090e3731302e553a27c5d3e4df1f0d76beaff06
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+93
View File
@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
set -euo pipefail
# Run from any directory. The executable argument must be an absolute native path.
aie_binary=${1:?Usage: native-smoke.sh /absolute/path/to/ai-engineering}
aie_fixture=$(mktemp -d "${TMPDIR:-/tmp}/ai-engineering-smoke.XXXXXX")
if [[ "${AIE_KEEP_FIXTURE:-0}" != 1 ]]; then trap 'rm -rf "$aie_fixture"' EXIT; fi
cd "$aie_fixture"
"$aie_binary" --help > help.txt
"$aie_binary" --version > version.txt
grep -q 'ai-engineering 0.1.0' version.txt
if "$aie_binary" --unknown > invalid.txt 2>&1; then
echo 'Invalid arguments unexpectedly succeeded' >&2
exit 1
else
test "$?" -eq 2
fi
# Git initialization is fixture setup, never an implicit CLI operation.
git init -q runtime
git init -q studio
for aie_repo in runtime studio; do
git -C "$aie_repo" -c user.name=Fixture -c user.email=fixture@example.invalid \
commit -q --allow-empty -m fixture
done
"$aie_binary" init --name 'Continuity Experiment' > init.yaml
"$aie_binary" repo add runtime --path runtime --language rust > runtime.yaml
"$aie_binary" repo add studio --path studio --language java > studio.yaml
"$aie_binary" work create 'Improve scene editor' --repo runtime --repo studio \
--goal 'Continue across agents' --constraint 'No server' \
--acceptance 'Fresh process reconstructs state' > work.yaml
"$aie_binary" discussion add WRK-0001 --kind QUESTION --author agent-a \
--text 'Evaluate Canvas rendering?' > discussion.yaml
printf 'Observed fixture result: 60 fps\n' > result.txt
"$aie_binary" artifact add WRK-0001 --file result.txt --purpose 'Rendering evidence' > artifact.yaml
"$aie_binary" decision draft WRK-0001 --title 'Evaluate layered Canvas' \
--evidence ART-0001 > decision.yaml
"$aie_binary" work context WRK-0001 --format json > before.json
mkdir -p studio/src/editor
cd studio/src/editor
"$aie_binary" work context WRK-0001 --format json > "$aie_fixture/after.json"
cd "$aie_fixture"
cmp before.json after.json
for aie_expected in runtime studio agent-a DRAFT sha256 'Continue across agents'; do
grep -q "$aie_expected" after.json
done
"$aie_binary" work context WRK-0001 --format markdown > context.md
"$aie_binary" project validate --format json > validation.json
grep -q '"valid" : true' validation.json
test ! -e .git
echo 'Native multi-repository continuity smoke passed.'
if [[ "${AIE_KEEP_FIXTURE:-0}" == 1 ]]; then echo "Fixture retained: $aie_fixture"; fi
+1
View File
@@ -0,0 +1 @@
rootProject.name = "ai-engineering"
@@ -0,0 +1,26 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.cli.EngineeringCli;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportRuntimeHints;
import java.io.PrintWriter;
import java.nio.file.Path;
@SpringBootApplication(proxyBeanMethods = false)
@ImportRuntimeHints(NativeHints.class)
public class AiEngineeringApplication {
@Bean EngineeringCli engineeringCli() { return new EngineeringCli(Path.of("")); }
public static void main(String[] args) {
var application = new SpringApplication(AiEngineeringApplication.class);
application.setWebApplicationType(WebApplicationType.NONE);
int exit;
// Picocli owns argument parsing; passing user arguments to Spring could change application policy.
try (var context = application.run()) {
exit = context.getBean(EngineeringCli.class).execute(new PrintWriter(System.out, true), new PrintWriter(System.err, true), args);
}
System.exit(exit);
}
}
@@ -0,0 +1,19 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.*;
import net.intrepid.aiengineering.artifact.*;
import net.intrepid.aiengineering.verification.*;
import org.springframework.aot.hint.*;
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,
ProjectConfig.Access.class, ProjectService.Revision.class, Work.class, WorkService.Sequence.class, DiscussionEntry.class,
DraftDecision.class, Artifact.class, ValidationReport.class, VerificationService.Context.class}) {
hints.reflection().registerType(type, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_METHODS);
}
}
}
@@ -0,0 +1,15 @@
package net.intrepid.aiengineering.artifact;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.work.Work;
import java.time.Instant;
public record Artifact(int schemaVersion, String id, String workId, String origin, String purpose, String path,
String sha256, long size, String author, String createdAt) {
public Artifact {
ProtocolException.schema(schemaVersion); Work.identifier(id, "ART"); Work.identifier(workId, "WRK");
ProtocolException.text(origin, "origin"); ProtocolException.text(purpose, "purpose");
ProtocolException.text(path, "artifact path"); ProtocolException.text(author, "author"); Instant.parse(createdAt);
if (sha256 == null || !sha256.matches("[a-f0-9]{64}") || size < 0) throw ProtocolException.validation("Invalid artifact integrity metadata");
}
}
@@ -0,0 +1,56 @@
package net.intrepid.aiengineering.artifact;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.work.*;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
public final class ArtifactService {
public static final long MAX_BYTES = 1024 * 1024;
private final WorkService works = new WorkService();
public List<Artifact> list(Path root, String id) {
var work = works.load(root, id); Path folder = works.folder(root, id);
return work.artifacts().stream().map(ref -> {
var artifact = Documents.read(Filespace.resolve(folder, "artifacts/evidence/" + ref + "/artifact.yaml"), Artifact.class);
if (!artifact.id().equals(ref) || !artifact.workId().equals(id)) throw ProtocolException.validation("Artifact identity mismatch: " + ref);
String expected = "artifacts/evidence/" + ref + "/payload";
if (!artifact.path().equals(expected)) throw ProtocolException.validation("Invalid artifact payload reference: " + artifact.path());
return artifact;
}).toList();
}
public Artifact attach(Path root, String workId, Path source, String purpose, String origin, String author) {
if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.missing("Evidence source is not a regular file: " + source);
if (Filespace.io(() -> Files.size(source)) > MAX_BYTES) throw ProtocolException.invalid("Evidence exceeds 1 MiB; reference large resources instead");
byte[] bytes = Filespace.io(() -> {
try (var input = Files.newInputStream(source)) { return input.readNBytes((int) MAX_BYTES + 1); }
});
if (bytes.length > MAX_BYTES) throw ProtocolException.invalid("Evidence exceeds 1 MiB");
return Filespace.locked(root, () -> {
var work = works.load(root, workId); String id = works.nextReference(work.artifacts(), "ART");
Path folder = works.folder(root, workId);
Path parent = Filespace.resolve(folder, "artifacts/evidence");
Path stage = Filespace.resolve(parent, "." + id + "-" + UUID.randomUUID() + ".tmp"); Filespace.directory(stage);
var artifact = new Artifact(1, id, workId, origin == null ? source.getFileName().toString() : origin, purpose,
"artifacts/evidence/" + id + "/payload", hash(bytes), bytes.length, author, Instant.now().toString());
Filespace.writeBytes(stage.resolve("payload"), bytes, false);
Filespace.write(stage.resolve("artifact.yaml"), Documents.yaml(artifact), false);
Filespace.moveDirectory(stage, Filespace.resolve(parent, id));
works.addReference(root, workId, "artifacts", id); return artifact;
});
}
public void validate(Path root, String id) {
for (var artifact : list(root, id)) {
Path path = Filespace.resolve(works.folder(root, id), artifact.path());
if (!Files.isRegularFile(path)) throw ProtocolException.validation("Missing artifact payload: " + artifact.path());
if (Filespace.io(() -> Files.size(path)) != artifact.size() || artifact.size() > MAX_BYTES)
throw ProtocolException.validation("Artifact size mismatch: " + artifact.id());
if (!hash(Filespace.io(() -> Files.readAllBytes(path))).equals(artifact.sha256()))
throw ProtocolException.validation("Artifact SHA-256 mismatch: " + artifact.id());
}
}
private static String hash(byte[] bytes) {
try { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); }
catch (java.security.NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
package net.intrepid.aiengineering.artifact;
@@ -0,0 +1,150 @@
package net.intrepid.aiengineering.cli;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.*;
import net.intrepid.aiengineering.artifact.*;
import net.intrepid.aiengineering.verification.*;
import picocli.CommandLine;
import picocli.CommandLine.*;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.List;
@Command(name = "ai-engineering", description = "Portable engineering protocol for humans and AI agents.",
mixinStandardHelpOptions = true, version = "ai-engineering 0.1.0")
public final class EngineeringCli implements Runnable {
private final Path cwd;
private final ProjectService projects = new ProjectService();
private final WorkService works = new WorkService();
private final VerificationService verification = new VerificationService();
private PrintWriter output;
private CommandLine commandLine;
@Option(names = "--project", scope = ScopeType.INHERIT, description = "Engineering project root or .ai-engineering directory.") Path project;
public EngineeringCli(Path cwd) { this.cwd = cwd.toAbsolutePath().normalize(); }
public int execute(PrintWriter out, PrintWriter err, String... args) {
output = out;
commandLine = new CommandLine(this)
.addSubcommand("project", new ProjectCommands()).addSubcommand("repo", new RepoCommands())
.addSubcommand("work", new WorkCommands()).addSubcommand("discussion", new DiscussionCommands())
.addSubcommand("decision", new DecisionCommands()).addSubcommand("artifact", new ArtifactCommands());
configure(commandLine, out, err);
commandLine.setExecutionExceptionHandler((exception, command, parse) -> {
if (exception instanceof ProtocolException problem) { err.println(problem.getMessage()); return problem.exitCode(); }
if (exception instanceof IllegalArgumentException) { err.println("Invalid input: " + exception.getMessage()); return 2; }
err.println("Operation failed: " + exception.getMessage()); return 1;
});
int result = commandLine.execute(args); out.flush(); err.flush(); return result;
}
private void configure(CommandLine command, PrintWriter out, PrintWriter err) {
command.setOut(out).setErr(err).setCaseInsensitiveEnumValuesAllowed(true);
command.getSubcommands().values().forEach(child -> configure(child, out, err));
}
@Override public void run() { commandLine.usage(output); }
private Path root() { return projects.discover(cwd, project == null ? null : resolve(project)); }
private Path resolve(Path path) { return path.isAbsolute() ? path : cwd.resolve(path); }
enum Format { markdown, json }
private int emit(Object value, Format format) {
output.print(format == Format.json ? Documents.json(value) : Documents.yaml(value)); return 0;
}
private int report(ValidationReport report, Format format) { emit(report, format); return report.valid() ? 0 : 4; }
@Command(name = "init", mixinStandardHelpOptions = true, description = "Initialize protocol files without modifying Git.")
int init(@Option(names = "--name", required = true) String name) {
Path target = project == null ? cwd : resolve(project);
return emit(projects.initialize(target, name), Format.markdown);
}
@Command(name = "project", mixinStandardHelpOptions = true, description = "Inspect and validate the engineering project.")
public class ProjectCommands {
@Command(name = "show", mixinStandardHelpOptions = true)
int show(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()), format); }
@Command(name = "validate", mixinStandardHelpOptions = true)
int validate(@Option(names = "--format", defaultValue = "markdown") Format format) { return report(verification.project(root()), format); }
}
@Command(name = "repo", mixinStandardHelpOptions = true, description = "Register existing source repositories; default access is read-only.")
public class RepoCommands {
@Command(name = "add", mixinStandardHelpOptions = true)
int add(@Parameters(index = "0") String id, @Option(names = "--path", required = true) String path,
@Option(names = "--type", defaultValue = "linked-git") String type,
@Option(names = "--language") String language, @Option(names = "--allow-edit") boolean edit,
@Option(names = "--validation-command") List<String> commands) {
var repo = new ProjectConfig.Repository(id, path, type, language, new ProjectConfig.Access(true, edit), commands);
return emit(projects.addRepository(root(), repo), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(projects.load(root()).repositories(), format); }
}
@Command(name = "work", mixinStandardHelpOptions = true, description = "Create, inspect, validate and export Works.")
public class WorkCommands {
@Command(name = "create", mixinStandardHelpOptions = true)
int create(@Parameters(index = "0") String title,
@Option(names = "--description", defaultValue = "") String description,
@Option(names = "--goal", defaultValue = "") String goal,
@Option(names = "--motivation", defaultValue = "") String motivation,
@Option(names = "--constraint") List<String> constraints,
@Option(names = "--acceptance") List<String> criteria,
@Option(names = "--repo") List<String> repositories,
@Option(names = "--author", defaultValue = "human") String author) {
return emit(works.create(root(), title, description, goal, motivation, safe(constraints), safe(criteria), safe(repositories), author), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Option(names = "--format", defaultValue = "markdown") Format format) { return emit(works.list(root()), format); }
@Command(name = "show", mixinStandardHelpOptions = true)
int show(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) { return emit(works.load(root(), id), format); }
@Command(name = "validate", mixinStandardHelpOptions = true)
int validate(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
Work.identifier(id, "WRK"); Path root = root(); works.load(root, id); return report(verification.work(root, id), format);
}
@Command(name = "context", mixinStandardHelpOptions = true)
int context(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
Work.identifier(id, "WRK"); Path root = root(); works.load(root, id);
var context = verification.context(root, id);
output.print(format == Format.json ? Documents.json(context) : verification.markdown(context)); return 0;
}
@Command(name = "status", mixinStandardHelpOptions = true, description = "Set lifecycle status; transitions remain reversible.")
int status(@Parameters(index = "0") String id, @Parameters(index = "1") Work.Status status) { return emit(works.status(root(), id, status), Format.markdown); }
}
@Command(name = "discussion", mixinStandardHelpOptions = true, description = "Append human or agent refinement entries.")
public class DiscussionCommands {
@Command(name = "add", mixinStandardHelpOptions = true)
int add(@Parameters(index = "0") String id, @Option(names = "--text", required = true) String text,
@Option(names = "--kind", defaultValue = "NOTE") DiscussionEntry.Kind kind,
@Option(names = "--author", defaultValue = "human") String author,
@Option(names = "--discussion", defaultValue = "main") String thread,
@Option(names = "--responds-to") String respondsTo) {
return emit(new DiscussionService().add(root(), id, text, kind, author, thread, respondsTo), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
return emit(new DiscussionService().list(root(), id), format);
}
}
@Command(name = "decision", mixinStandardHelpOptions = true, description = "Persist draft formal decisions.")
public class DecisionCommands {
@Command(name = "draft", mixinStandardHelpOptions = true)
int draft(@Parameters(index = "0") String id, @Option(names = "--title", required = true) String title,
@Option(names = "--context", defaultValue = "") String context,
@Option(names = "--approach", defaultValue = "") String approach,
@Option(names = "--rationale", defaultValue = "") String rationale,
@Option(names = "--evidence") List<String> evidence,
@Option(names = "--author", defaultValue = "human") String author) {
return emit(new DecisionService().draft(root(), id, title, context, approach, rationale, safe(evidence), author), Format.markdown);
}
@Command(name = "list", mixinStandardHelpOptions = true)
int list(@Parameters(index = "0") String id, @Option(names = "--format", defaultValue = "markdown") Format format) {
return emit(new DecisionService().list(root(), id), format);
}
}
@Command(name = "artifact", mixinStandardHelpOptions = true, description = "Attach small evidence files with integrity metadata.")
public class ArtifactCommands {
@Command(name = "add", mixinStandardHelpOptions = true)
int add(@Parameters(index = "0") String id, @Option(names = "--file", required = true) Path file,
@Option(names = "--purpose", required = true) String purpose, @Option(names = "--origin") String origin,
@Option(names = "--author", defaultValue = "human") String author) {
return emit(new ArtifactService().attach(root(), id, resolve(file), purpose, origin, author), Format.markdown);
}
}
private static <T> List<T> safe(List<T> list) { return list == null ? List.of() : list; }
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact", "verification"})
package net.intrepid.aiengineering.cli;
@@ -0,0 +1,30 @@
package net.intrepid.aiengineering.decision;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.work.*;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
public final class DecisionService {
private final WorkService works = new WorkService();
public List<DraftDecision> list(Path root, String id) {
var work = works.load(root, id); Path folder = works.folder(root, id);
return work.decisions().stream().map(ref -> {
var decision = Documents.readDocument(Filespace.resolve(folder, "decisions/" + ref + ".md"), DraftDecision.class);
if (!decision.id().equals(ref) || !decision.workId().equals(id)) throw ProtocolException.validation("Decision identity mismatch: " + ref);
return decision;
}).toList();
}
public DraftDecision draft(Path root, String workId, String title, String context, String approach, String rationale, List<String> evidence, String author) {
return Filespace.locked(root, () -> {
var work = works.load(root, workId);
if (!work.artifacts().containsAll(evidence)) throw ProtocolException.invalid("Decision references an unknown artifact");
String id = works.nextReference(work.decisions(), "DEC");
var decision = new DraftDecision(1, id, workId, title, context, approach, List.of(), rationale, List.of(), List.of(),
"DRAFT", author, Instant.now().toString(), evidence);
Documents.writeDocument(Filespace.resolve(works.folder(root, workId), "decisions/" + id + ".md"), decision, false);
works.addReference(root, workId, "decisions", id); return decision;
});
}
}
@@ -0,0 +1,20 @@
package net.intrepid.aiengineering.decision;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.work.Work;
import java.time.Instant;
import java.util.List;
public record DraftDecision(int schemaVersion, String id, String workId, String title, String context,
String approach, List<String> alternatives, String rationale, List<String> risks, List<String> acceptanceCriteria,
String approvalStatus, String author, String createdAt, List<String> evidence) {
public DraftDecision {
ProtocolException.schema(schemaVersion); Work.identifier(id, "DEC"); Work.identifier(workId, "WRK");
ProtocolException.text(title, "decision title"); ProtocolException.text(author, "author"); Instant.parse(createdAt);
if (!"DRAFT".equals(approvalStatus)) throw ProtocolException.validation("Milestone 1 only supports DRAFT decisions");
if (context == null || approach == null || rationale == null) throw ProtocolException.validation("Missing decision fields");
alternatives = List.copyOf(alternatives); risks = List.copyOf(risks);
acceptanceCriteria = List.copyOf(acceptanceCriteria); evidence = List.copyOf(evidence);
evidence.forEach(idValue -> Work.identifier(idValue, "ART"));
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
package net.intrepid.aiengineering.decision;
@@ -0,0 +1,17 @@
package net.intrepid.aiengineering.discussion;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.work.Work;
import java.time.Instant;
public record DiscussionEntry(int schemaVersion, String id, String workId, String discussionId, Kind kind,
String author, String createdAt, String respondsTo, String text) {
public enum Kind { NOTE, QUESTION, RESPONSE, SUGGESTION, ASSUMPTION, HYPOTHESIS, INVESTIGATION, ALTERNATIVE, ISSUE, CONCLUSION }
public DiscussionEntry {
ProtocolException.schema(schemaVersion); Work.identifier(id, "DSC"); Work.identifier(workId, "WRK");
ProtocolException.text(discussionId, "discussionId"); ProtocolException.text(author, "author");
ProtocolException.text(text, "discussion text"); Instant.parse(createdAt);
if (kind == null) throw ProtocolException.validation("Missing discussion kind");
if (respondsTo != null) Work.identifier(respondsTo, "DSC");
}
}
@@ -0,0 +1,30 @@
package net.intrepid.aiengineering.discussion;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.work.*;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
public final class DiscussionService {
private final WorkService works = new WorkService();
public List<DiscussionEntry> list(Path root, String id) {
Work work = works.load(root, id); Path folder = works.folder(root, id);
return work.discussions().stream().map(ref -> {
var entry = Documents.readDocument(Filespace.resolve(folder, "discussions/" + ref + ".md"), DiscussionEntry.class);
if (!entry.id().equals(ref) || !entry.workId().equals(id)) throw ProtocolException.validation("Discussion identity mismatch: " + ref);
return entry;
}).toList();
}
public DiscussionEntry add(Path root, String workId, String text, DiscussionEntry.Kind kind, String author, String discussionId, String respondsTo) {
return Filespace.locked(root, () -> {
var work = works.load(root, workId);
if (respondsTo != null && list(root, workId).stream().noneMatch(e -> e.id().equals(respondsTo)))
throw ProtocolException.invalid("Response target not found in Work: " + respondsTo);
String id = works.nextReference(work.discussions(), "DSC");
var entry = new DiscussionEntry(1, id, workId, discussionId, kind, author, Instant.now().toString(), respondsTo, text);
Documents.writeDocument(Filespace.resolve(works.folder(root, workId), "discussions/" + id + ".md"), entry, false);
works.addReference(root, workId, "discussions", id); return entry;
});
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "work"})
package net.intrepid.aiengineering.discussion;
@@ -0,0 +1,35 @@
package net.intrepid.aiengineering.filesystem;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.dataformat.yaml.YAMLMapper;
import tools.jackson.core.StreamReadFeature;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.cfg.EnumFeature;
import java.nio.file.Path;
/** Explicit protocol records, never Spring internal objects, are canonical. */
public final class Documents {
private static final YAMLMapper YAML = YAMLMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
DeserializationFeature.FAIL_ON_TRAILING_TOKENS).enable(EnumFeature.FAIL_ON_NUMBERS_FOR_ENUMS).build();
private static final JsonMapper JSON = JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build();
private Documents() {}
public static String yaml(Object value) { return YAML.writeValueAsString(value); }
public static String json(Object value) { return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value) + "\n"; }
public static <T> T parse(String yaml, Class<T> type) {
try { return YAML.readValue(yaml, type); }
catch (RuntimeException e) { throw ProtocolException.validation("Invalid " + type.getSimpleName() + ": " + e.getMessage()); }
}
public static <T> T read(Path path, Class<T> type) { return parse(Filespace.read(path), type); }
public static <T> T readDocument(Path path, Class<T> type) {
String text = Filespace.read(path);
if (!text.startsWith("---\n")) throw ProtocolException.validation("Missing YAML front matter: " + path);
int end = text.indexOf("\n---\n", 4);
if (end < 0) throw ProtocolException.validation("Unclosed YAML front matter: " + path);
return parse(text.substring(4, end), type);
}
public static void writeDocument(Path path, Object value, boolean replace) {
String yaml = yaml(value).replaceFirst("^---\\n", "");
Filespace.write(path, "---\n" + yaml + "---\n", replace);
}
}
@@ -0,0 +1,84 @@
package net.intrepid.aiengineering.filesystem;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardOpenOption.*;
/** Filesystem operations shared by the protocol adapters. Never executes project commands. */
public final class Filespace {
private Filespace() {}
@FunctionalInterface public interface IoSupplier<T> { T get() throws IOException; }
public static <T> T io(IoSupplier<T> action) {
try { return action.get(); }
catch (NoSuchFileException e) { throw ProtocolException.missing("Missing file: " + e.getFile()); }
catch (IOException e) { throw new ProtocolException(1, "Filesystem operation failed: " + e.getMessage()); }
}
/** Rejects traversal and symlinks at every component, including paths that do not yet exist. */
public static Path resolve(Path root, String relative) {
Path value = Path.of(ProtocolException.text(relative, "path"));
if (value.isAbsolute() || relative.contains("\\")) throw ProtocolException.invalid("Expected a relative path: " + relative);
for (Path part : value) if (part.toString().equals("..")) throw ProtocolException.invalid("Path traversal rejected: " + relative);
Path base = root.toAbsolutePath().normalize();
Path result = base.resolve(value).normalize();
if (!result.startsWith(base)) throw ProtocolException.invalid("Path escapes project: " + relative);
Path current = base;
if (Files.isSymbolicLink(base)) throw ProtocolException.invalid("Symlink rejected: " + base);
for (Path part : base.relativize(result)) {
current = current.resolve(part);
if (Files.isSymbolicLink(current)) throw ProtocolException.invalid("Symlink rejected: " + current);
}
return result;
}
public static void directory(Path path) { io(() -> { Files.createDirectories(path); return null; }); }
public static List<Path> children(Path directory) {
return io(() -> { try (var stream = Files.list(directory)) {
return stream.filter(p -> !p.getFileName().toString().startsWith(".")).sorted().toList();
}});
}
public static String read(Path path) { return io(() -> Files.readString(path)); }
public static void write(Path path, String content, boolean replace) {
writeBytes(path, content.getBytes(java.nio.charset.StandardCharsets.UTF_8), replace);
}
public static void writeBytes(Path path, byte[] bytes, boolean replace) {
io(() -> {
if (Files.exists(path, NOFOLLOW_LINKS) && !replace) throw ProtocolException.invalid("Already exists: " + path);
if (Files.isSymbolicLink(path)) throw ProtocolException.invalid("Symlink rejected: " + path);
Path temp = path.resolveSibling("." + path.getFileName() + "." + UUID.randomUUID() + ".tmp");
try {
try (var channel = FileChannel.open(temp, CREATE_NEW, WRITE)) {
var buffer = java.nio.ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
if (replace) Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
else {
// A hard link publishes the complete file atomically and cannot overwrite a competing writer.
Files.createLink(path, temp);
}
} finally { Files.deleteIfExists(temp); }
return null;
});
}
public static <T> T locked(Path projectRoot, Supplier<T> operation) {
Path lock = resolve(projectRoot, ".ai-engineering/.local/write.lock");
directory(lock.getParent());
return io(() -> {
try (var channel = FileChannel.open(lock, CREATE, WRITE, NOFOLLOW_LINKS); var ignored = channel.lock()) {
return operation.get();
} catch (java.nio.channels.OverlappingFileLockException e) {
throw ProtocolException.invalid("Project is being modified by this process; retry after it completes");
}
});
}
public static void moveDirectory(Path from, Path to) {
io(() -> {
if (Files.exists(to, NOFOLLOW_LINKS)) throw ProtocolException.invalid("Already exists: " + to);
Files.move(from, to, StandardCopyOption.ATOMIC_MOVE); return null;
});
}
}
@@ -0,0 +1,17 @@
package net.intrepid.aiengineering.filesystem;
public final class ProtocolException extends RuntimeException {
private final int exitCode;
public ProtocolException(int exitCode, String message) { super(message); this.exitCode = exitCode; }
public int exitCode() { return exitCode; }
public static ProtocolException invalid(String message) { return new ProtocolException(2, message); }
public static ProtocolException missing(String message) { return new ProtocolException(3, message); }
public static ProtocolException validation(String message) { return new ProtocolException(4, message); }
public static String text(String value, String field) {
if (value == null || value.isBlank()) throw invalid(field + " must not be blank");
return value;
}
public static void schema(int version) {
if (version != 1) throw validation("Unsupported or missing schemaVersion: " + version);
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {})
package net.intrepid.aiengineering.filesystem;
@@ -0,0 +1,32 @@
package net.intrepid.aiengineering.project;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import java.util.List;
public record ProjectConfig(int schemaVersion, Identity project, List<Repository> repositories) {
public ProjectConfig {
ProtocolException.schema(schemaVersion);
if (project == null || repositories == null) throw ProtocolException.validation("project and repositories are required");
repositories = List.copyOf(repositories);
if (repositories.stream().map(Repository::id).distinct().count() != repositories.size())
throw ProtocolException.validation("Duplicate repository IDs");
}
public record Identity(String id, String name) {
public Identity { identifier(id); ProtocolException.text(name, "project name"); }
}
public record Access(boolean read, boolean edit) {
public Access { if (edit && !read) throw ProtocolException.invalid("edit access requires read access"); }
}
public record Repository(String id, String path, String type, String language, Access access, List<String> validationCommands) {
public Repository {
identifier(id); ProtocolException.text(path, "repository path");
if (!List.of("linked-git", "git-submodule").contains(type == null ? "" : type))
throw ProtocolException.invalid("Repository type must be linked-git or git-submodule");
access = access == null ? new Access(true, false) : access;
validationCommands = validationCommands == null ? List.of() : List.copyOf(validationCommands);
}
}
public static void identifier(String id) {
if (id == null || !id.matches("[a-z][a-z0-9-]{0,63}")) throw ProtocolException.invalid("Invalid identifier: " + id);
}
}
@@ -0,0 +1,93 @@
package net.intrepid.aiengineering.project;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.internal.*;
import java.nio.file.*;
import java.util.*;
public final class ProjectService {
private final GitAdapter git = new ProcessGitAdapter();
public Path discover(Path start, Path explicit) {
if (explicit != null) {
Path root = canonical(explicit);
if (root.getFileName().toString().equals(".ai-engineering")) root = root.getParent();
requireConfig(root); return root;
}
for (Path current = canonical(start); current != null; current = current.getParent()) {
if (Files.exists(current.resolve(".ai-engineering"), LinkOption.NOFOLLOW_LINKS)) {
requireConfig(current); return current;
}
}
throw ProtocolException.missing("Engineering project not found; run ai-engineering init or use --project");
}
private static Path canonical(Path path) { return Filespace.io(() -> path.toAbsolutePath().normalize().toRealPath()); }
private void requireConfig(Path root) {
Path file = Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml");
if (!Files.isRegularFile(file)) throw ProtocolException.missing("Missing project configuration: " + file);
}
public ProjectConfig initialize(Path root, String name) {
root = canonical(root);
var identity = new ProjectConfig.Identity(slug(name), name);
var config = new ProjectConfig(1, identity, List.of());
Path target = Filespace.resolve(root, ".ai-engineering");
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) throw ProtocolException.invalid("Project already exists: " + target);
Path staging = Filespace.resolve(root, ".ai-engineering-init-" + UUID.randomUUID());
Filespace.directory(staging);
for (String dir : List.of("works", "contracts", ".local")) Filespace.directory(staging.resolve(dir));
Filespace.write(staging.resolve("ai-engineering.yaml"), Documents.yaml(config), false);
Filespace.write(staging.resolve(".gitignore"), ".local/\nworks/.*.tmp\nworks/*/runs/\n", false);
Filespace.moveDirectory(staging, target);
return config;
}
public static String slug(String text) {
ProtocolException.text(text, "name");
String result = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFD)
.replaceAll("\\p{M}", "").toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-|-$", "");
if (result.isBlank()) result = "project";
if (!Character.isLetter(result.charAt(0))) result = "p-" + result;
return result.substring(0, Math.min(result.length(), 60)).replaceAll("-$", "");
}
public ProjectConfig load(Path root) { return Documents.read(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), ProjectConfig.class); }
public ProjectConfig addRepository(Path root, ProjectConfig.Repository repository) {
return Filespace.locked(root, () -> {
var config = load(root);
if (config.repositories().stream().anyMatch(r -> r.id().equals(repository.id()))) throw ProtocolException.invalid("Repository already registered: " + repository.id());
Path path = repositoryPath(root, repository);
if (config.repositories().stream().anyMatch(r -> repositoryPath(root, r).equals(path))) throw ProtocolException.invalid("Repository path already registered: " + path);
git.inspect(root, path, repository.type());
var repositories = new ArrayList<>(config.repositories()); repositories.add(repository);
var updated = new ProjectConfig(1, config.project(), repositories);
Filespace.write(Filespace.resolve(root, ".ai-engineering/ai-engineering.yaml"), Documents.yaml(updated), true);
return updated;
});
}
public Path repositoryPath(Path root, ProjectConfig.Repository repository) {
Path path = Filespace.resolve(root, repository.path());
if (path.equals(root) || path.startsWith(root.resolve(".ai-engineering"))) throw ProtocolException.invalid("Repository must be a source directory beneath project root");
return path;
}
public void validate(Path root) {
var config = load(root); var paths = new HashSet<Path>();
for (var repo : config.repositories()) {
Path path = repositoryPath(root, repo);
if (!paths.add(path)) throw ProtocolException.validation("Duplicate repository path: " + repo.path());
git.inspect(root, path, repo.type());
}
}
public record Revision(String repositoryId, String path, String head, boolean dirty) {
public Revision {
ProjectConfig.identifier(repositoryId); ProtocolException.text(path, "repository snapshot path");
if (head == null || !head.matches("UNBORN|[a-f0-9]{40}|[a-f0-9]{64}"))
throw ProtocolException.validation("Invalid repository revision: " + head);
}
}
public List<Revision> revisions(Path root, List<String> ids) {
var config = load(root);
return ids.stream().map(id -> {
var repo = config.repositories().stream().filter(r -> r.id().equals(id)).findFirst()
.orElseThrow(() -> ProtocolException.validation("Unknown repository: " + id));
var snapshot = git.inspect(root, repositoryPath(root, repo), repo.type());
return new Revision(id, repo.path(), snapshot.head(), snapshot.dirty());
}).toList();
}
}
@@ -0,0 +1,7 @@
package net.intrepid.aiengineering.project.internal;
import java.nio.file.Path;
public interface GitAdapter {
record Snapshot(String head, boolean dirty) {}
Snapshot inspect(Path root, Path repository, String type);
}
@@ -0,0 +1,53 @@
package net.intrepid.aiengineering.project.internal;
import net.intrepid.aiengineering.filesystem.*;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;
/** Read-only Git adapter. No init, checkout, submodule update, commit or network operations. */
public final class ProcessGitAdapter implements GitAdapter {
private String git(Path path, String... args) {
return Filespace.io(() -> {
var command = new java.util.ArrayList<String>(java.util.List.of("git", "--no-optional-locks", "-C", path.toString()));
command.addAll(java.util.List.of(args));
var builder = new ProcessBuilder(command).redirectErrorStream(true);
builder.environment().keySet().removeIf(k -> k.startsWith("GIT_"));
var process = builder.start();
String output;
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
var reader = executor.submit(() -> {
try (var input = process.getInputStream()) {
byte[] prefix = input.readNBytes(65536);
input.transferTo(java.io.OutputStream.nullOutputStream());
return new String(prefix, java.nio.charset.StandardCharsets.UTF_8).strip();
}
});
try {
if (!process.waitFor(10, TimeUnit.SECONDS)) { process.destroyForcibly(); throw ProtocolException.validation("Git inspection timed out: " + path); }
output = reader.get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
process.destroyForcibly(); Thread.currentThread().interrupt(); throw new java.io.IOException("Git inspection interrupted", e);
} catch (java.util.concurrent.ExecutionException | java.util.concurrent.TimeoutException e) {
process.destroyForcibly(); throw new java.io.IOException("Cannot read Git inspection output", e);
}
}
if (process.exitValue() != 0) throw ProtocolException.validation("Git inspection failed: " + output);
return output;
});
}
@Override public Snapshot inspect(Path root, Path repository, String type) {
if (!Files.isDirectory(repository)) throw ProtocolException.missing("Missing repository: " + repository);
Path actual = Path.of(git(repository, "rev-parse", "--show-toplevel"));
if (!Filespace.io(actual::toRealPath).equals(Filespace.io(repository::toRealPath)))
throw ProtocolException.validation("Not an independent Git repository: " + repository);
if (type.equals("git-submodule")) {
String superproject = git(repository, "rev-parse", "--show-superproject-working-tree");
if (superproject.isBlank() || !Filespace.io(() -> Path.of(superproject).toRealPath()).equals(Filespace.io(root::toRealPath)))
throw ProtocolException.validation("Repository is not a submodule of this project: " + repository);
}
String head;
try { head = git(repository, "rev-parse", "--verify", "HEAD"); }
catch (ProtocolException e) { head = "UNBORN"; }
return new Snapshot(head, !git(repository, "status", "--porcelain", "--untracked-files=normal").isBlank());
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = "filesystem")
package net.intrepid.aiengineering.project;
@@ -0,0 +1,5 @@
package net.intrepid.aiengineering.verification;
import java.util.List;
public record ValidationReport(boolean valid, List<String> issues) {
public ValidationReport { issues = List.copyOf(issues); }
}
@@ -0,0 +1,101 @@
package net.intrepid.aiengineering.verification;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.work.*;
import net.intrepid.aiengineering.discussion.*;
import net.intrepid.aiengineering.decision.*;
import net.intrepid.aiengineering.artifact.*;
import java.nio.file.*;
import java.util.*;
public final class VerificationService {
private final ProjectService projects = new ProjectService();
private final WorkService works = new WorkService();
private final DiscussionService discussions = new DiscussionService();
private final DecisionService decisions = new DecisionService();
private final ArtifactService artifacts = new ArtifactService();
private void check(List<String> issues, Runnable operation) {
try { operation.run(); } catch (RuntimeException e) { issues.add(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); }
}
public ValidationReport project(Path root) {
var issues = new ArrayList<String>();
check(issues, () -> projects.validate(root));
check(issues, () -> {
var all = works.list(root);
Path counter = Filespace.resolve(works.workspace(root), ".sequence.yaml");
if (!all.isEmpty()) {
var sequence = Documents.read(counter, WorkService.Sequence.class);
long max = all.stream().mapToLong(w -> Long.parseLong(w.id().substring(4))).max().orElse(0);
if (sequence.lastWork() < max) issues.add("Work sequence is below the highest reserved ID");
}
all.forEach(w -> issues.addAll(work(root, w.id()).issues()));
});
for (String directory : List.of("works", "contracts", ".local"))
check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(root, ".ai-engineering/" + directory))) issues.add("Missing project directory: " + directory); });
return new ValidationReport(issues.isEmpty(), issues);
}
public ValidationReport work(Path root, String id) {
var issues = new ArrayList<String>();
check(issues, () -> {
Work work = works.load(root, id); Path folder = works.folder(root, id);
var registered = projects.load(root).repositories().stream().map(ProjectConfig.Repository::id).toList();
for (var revision : work.repositories()) {
if (!registered.contains(revision.repositoryId())) issues.add("Unknown Work repository: " + revision.repositoryId());
check(issues, () -> Filespace.resolve(root, revision.path()));
}
for (String directory : List.of("discussions", "decisions", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
check(issues, () -> { if (!Files.isDirectory(Filespace.resolve(folder, directory))) issues.add("Missing Work directory: " + directory); });
check(issues, () -> {
var entries = discussions.list(root, id);
var seen = new HashSet<String>();
for (var entry : entries) {
if (entry.respondsTo() != null && !seen.contains(entry.respondsTo())) issues.add("Discussion response must reference an earlier entry: " + entry.id());
seen.add(entry.id());
}
});
check(issues, () -> decisions.list(root, id).forEach(d -> {
if (!work.artifacts().containsAll(d.evidence())) issues.add("Missing decision evidence: " + d.id());
}));
check(issues, () -> artifacts.validate(root, id));
check(issues, () -> orphans(issues, folder, "discussions", work.discussions().stream().map(s -> s + ".md").toList()));
check(issues, () -> orphans(issues, folder, "decisions", work.decisions().stream().map(s -> s + ".md").toList()));
check(issues, () -> orphans(issues, folder, "artifacts/evidence", work.artifacts()));
});
return new ValidationReport(issues.isEmpty(), issues);
}
private void orphans(List<String> issues, Path folder, String directory, List<String> expected) {
for (Path entry : Filespace.children(Filespace.resolve(folder, directory))) {
Filespace.resolve(folder, folder.relativize(entry).toString());
if (!expected.contains(entry.getFileName().toString())) issues.add("Unreferenced protocol file: " + directory + "/" + entry.getFileName());
}
}
public record Context(int schemaVersion, Work work, List<DiscussionEntry> discussionHistory, List<DraftDecision> decisions,
List<String> outstandingQuestions, List<Artifact> artifacts) {}
public Context context(Path root, String id) {
var report = work(root, id);
if (!report.valid()) throw ProtocolException.validation(String.join("; ", report.issues()));
var history = discussions.list(root, id);
var answered = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.RESPONSE || e.kind() == DiscussionEntry.Kind.CONCLUSION)
.map(DiscussionEntry::respondsTo).filter(Objects::nonNull).toList();
var outstanding = history.stream().filter(e -> e.kind() == DiscussionEntry.Kind.QUESTION || e.kind() == DiscussionEntry.Kind.ISSUE)
.filter(e -> !answered.contains(e.id())).map(e -> e.id() + ": " + e.text()).toList();
return new Context(1, works.load(root, id), history, decisions.list(root, id), outstanding, artifacts.list(root, id));
}
public String markdown(Context context) {
var w = context.work();
var result = new StringBuilder("# " + w.id() + " — " + w.title() + "\n\nProtocol schema: 1\n\nStatus: " + w.status() + "\n");
section(result, "Goal", w.goal()); section(result, "Description", w.description()); section(result, "Motivation", w.motivation());
section(result, "Constraints", items(w.constraints())); section(result, "Acceptance criteria", items(w.acceptanceCriteria()));
section(result, "Repository revisions at Work creation", yaml(w.repositories()));
section(result, "Discussion history and conclusions", yaml(context.discussionHistory()));
section(result, "Decisions (approval status is explicit)", yaml(context.decisions()));
section(result, "Outstanding questions", items(context.outstandingQuestions()));
section(result, "Artifact references (paths relative to Work)", yaml(context.artifacts()));
section(result, "Metadata", "Created: " + w.createdAt() + "\n\nUpdated: " + w.updatedAt() + "\n\nAuthor: " + w.author());
return result.toString();
}
private static String items(List<String> values) { return values.isEmpty() ? "None recorded." : String.join("\n", values.stream().map(v -> "- " + v).toList()); }
private static String yaml(Object value) { return "```yaml\n" + Documents.yaml(value) + "```"; }
private static void section(StringBuilder out, String title, String body) { out.append("\n## ").append(title).append("\n\n").append(body.isBlank() ? "None recorded." : body).append('\n'); }
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project", "work", "discussion", "decision", "artifact"})
package net.intrepid.aiengineering.verification;
@@ -0,0 +1,47 @@
package net.intrepid.aiengineering.work;
import net.intrepid.aiengineering.filesystem.ProtocolException;
import net.intrepid.aiengineering.project.ProjectService.Revision;
import java.time.Instant;
import java.util.List;
public record Work(int schemaVersion, String id, String title, String description, String goal, String motivation,
List<String> constraints, List<String> acceptanceCriteria, Status status, String createdAt, String updatedAt,
String author, List<Revision> repositories, List<String> discussions, List<String> decisions, List<String> artifacts) {
public enum Status { OPEN, ACTIVE, BLOCKED, COMPLETED, CANCELLED }
public Work {
ProtocolException.schema(schemaVersion); identifier(id, "WRK");
ProtocolException.text(title, "title"); ProtocolException.text(goal, "goal"); ProtocolException.text(author, "author");
if (description == null || motivation == null || status == null) throw ProtocolException.validation("Missing Work fields");
Instant.parse(createdAt); Instant.parse(updatedAt);
constraints = List.copyOf(constraints); acceptanceCriteria = List.copyOf(acceptanceCriteria);
repositories = List.copyOf(repositories); discussions = List.copyOf(discussions);
decisions = List.copyOf(decisions); artifacts = List.copyOf(artifacts);
checkRefs(discussions, "DSC"); checkRefs(decisions, "DEC"); checkRefs(artifacts, "ART");
if (repositories.stream().map(Revision::repositoryId).distinct().count() != repositories.size())
throw ProtocolException.validation("Duplicate Work repository references");
}
private static void checkRefs(List<String> refs, String prefix) {
refs.forEach(id -> identifier(id, prefix));
if (refs.stream().distinct().count() != refs.size()) throw ProtocolException.validation("Duplicate " + prefix + " references");
}
public static void identifier(String id, String prefix) {
if (id == null || !id.matches(prefix + "-[0-9]{4,9}") || Long.parseLong(id.substring(4)) == 0)
throw ProtocolException.invalid("Invalid " + prefix + " identifier: " + id);
}
public Work reference(String kind, String reference) {
var refs = new java.util.ArrayList<>(switch (kind) {
case "discussions" -> discussions; case "decisions" -> decisions; case "artifacts" -> artifacts;
default -> throw ProtocolException.invalid("Invalid reference kind: " + kind);
});
refs.add(reference);
return new Work(1, id, title, description, goal, motivation, constraints, acceptanceCriteria, status,
createdAt, Instant.now().toString(), author, repositories,
kind.equals("discussions") ? refs : discussions, kind.equals("decisions") ? refs : decisions,
kind.equals("artifacts") ? refs : artifacts);
}
public Work withStatus(Status value) {
return new Work(1, id, title, description, goal, motivation, constraints, acceptanceCriteria, value,
createdAt, Instant.now().toString(), author, repositories, discussions, decisions, artifacts);
}
}
@@ -0,0 +1,77 @@
package net.intrepid.aiengineering.work;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.ProjectService;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
public final class WorkService {
private final ProjectService projects = new ProjectService();
public Path workspace(Path root) { return Filespace.resolve(root, ".ai-engineering/works"); }
public List<Work> list(Path root) {
var seen = new HashSet<String>(); var result = new ArrayList<Work>();
for (Path folder : Filespace.children(workspace(root))) {
Path safe = Filespace.resolve(root, root.relativize(folder).toString());
if (!Files.isDirectory(safe)) throw ProtocolException.validation("Unexpected file in works: " + folder);
var work = Documents.readDocument(Filespace.resolve(safe, "work.md"), Work.class);
if (!seen.add(work.id())) throw ProtocolException.validation("Duplicate Work ID: " + work.id());
if (!folder.getFileName().toString().startsWith(work.id() + "-")) throw ProtocolException.validation("Work directory/ID mismatch: " + folder);
result.add(work);
}
return result.stream().sorted(Comparator.comparing(Work::id)).toList();
}
public Work load(Path root, String id) {
Work.identifier(id, "WRK");
return list(root).stream().filter(w -> w.id().equals(id)).findFirst()
.orElseThrow(() -> ProtocolException.missing("Work not found: " + id));
}
public Path folder(Path root, String id) {
load(root, id);
return Filespace.children(workspace(root)).stream().filter(p -> p.getFileName().toString().startsWith(id + "-"))
.map(p -> Filespace.resolve(root, root.relativize(p).toString())).findFirst().orElseThrow();
}
public Work create(Path root, String title, String description, String goal, String motivation,
List<String> constraints, List<String> criteria, List<String> repositories, String author) {
return Filespace.locked(root, () -> {
list(root); // Refuse to allocate an ID in a corrupt project.
// The sequence is canonical; a crash may leave gaps, but identities are never reused.
Path counter = Filespace.resolve(workspace(root), ".sequence.yaml");
long last = Files.exists(counter) ? Documents.read(counter, Sequence.class).lastWork() : 0;
long max = list(root).stream().mapToLong(w -> Long.parseLong(w.id().substring(4))).max().orElse(0);
long next = Math.max(last, max) + 1;
if (next > 999999999) throw ProtocolException.validation("Work ID space exhausted");
String id = "WRK-%04d".formatted(next);
String now = Instant.now().toString();
var work = new Work(1, id, title, description, goal.isBlank() ? title : goal, motivation, constraints, criteria,
Work.Status.OPEN, now, now, author, projects.revisions(root, repositories), List.of(), List.of(), List.of());
Path target = Filespace.resolve(workspace(root), id + "-" + ProjectService.slug(title));
Path staging = Filespace.resolve(workspace(root), "." + id + "-" + UUID.randomUUID() + ".tmp");
Filespace.directory(staging);
for (String dir : List.of("discussions", "decisions", "artifacts/references", "artifacts/experiments", "artifacts/evidence", "artifacts/outputs", "runs"))
Filespace.directory(Filespace.resolve(staging, dir));
Documents.writeDocument(staging.resolve("work.md"), work, false);
// Reserve before publishing. A crash can leave a gap, never reuse a reserved identity.
Filespace.write(counter, Documents.yaml(new Sequence(1, next)), Files.exists(counter));
Filespace.moveDirectory(staging, target); return work;
});
}
public record Sequence(int schemaVersion, long lastWork) {
public Sequence { ProtocolException.schema(schemaVersion); if (lastWork < 0) throw ProtocolException.validation("Invalid Work sequence"); }
}
/** Called inside the caller's project lock after publishing the referenced file. */
public void addReference(Path root, String id, String kind, String reference) {
Documents.writeDocument(Filespace.resolve(folder(root, id), "work.md"), load(root, id).reference(kind, reference), true);
}
public Work status(Path root, String id, Work.Status value) {
return Filespace.locked(root, () -> {
Work updated = load(root, id).withStatus(value);
Documents.writeDocument(Filespace.resolve(folder(root, id), "work.md"), updated, true); return updated;
});
}
public String nextReference(List<String> ids, String prefix) {
long max = ids.stream().mapToLong(id -> Long.parseLong(id.substring(4))).max().orElse(0);
if (max >= 999999999) throw ProtocolException.validation("ID space exhausted: " + prefix);
return prefix + "-%04d".formatted(max + 1);
}
}
@@ -0,0 +1,2 @@
@org.springframework.modulith.ApplicationModule(allowedDependencies = {"filesystem", "project"})
package net.intrepid.aiengineering.work;
@@ -0,0 +1,5 @@
spring.application.name=ai-engineering
spring.main.web-application-type=none
spring.main.banner-mode=off
spring.main.log-startup-info=false
logging.level.root=OFF
@@ -0,0 +1,6 @@
package net.intrepid.aiengineering;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
class ArchitectureTest {
@Test void moduleBoundariesAreValid() { ApplicationModules.of(AiEngineeringApplication.class).verify(); }
}
@@ -0,0 +1,74 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.cli.EngineeringCli;
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 IntegrityTest {
@TempDir Path root;
private String lastOutput;
private int cli(String... args) {
var out = new StringWriter(); var err = new StringWriter();
int code = new EngineeringCli(root).execute(new PrintWriter(out), new PrintWriter(err), args);
lastOutput = out + err.toString(); return code;
}
private void ok(String... args) { assertThat(cli(args)).as(lastOutput).isZero(); }
private Path work() { return root.resolve(".ai-engineering/works/WRK-0001-one"); }
private void initWork() { ok("init", "--name", "Test"); ok("work", "create", "One"); }
@Test void missingPayloadAndTamperedEvidenceAreDetected() throws Exception {
initWork(); Path source = Files.writeString(root.resolve("source.txt"), "abc");
ok("artifact", "add", "WRK-0001", "--file", source.toString(), "--purpose", "Test integrity");
Path payload = work().resolve("artifacts/evidence/ART-0001/payload");
Files.writeString(payload, "xyz");
assertThat(cli("work", "validate", "WRK-0001")).isEqualTo(4); assertThat(lastOutput).contains("SHA-256");
Files.delete(payload);
assertThat(cli("work", "validate", "WRK-0001")).isEqualTo(4); assertThat(lastOutput).contains("Missing artifact payload");
assertThat(cli("work", "context", "WRK-0001")).isEqualTo(4);
}
@Test void registeredRepositoryMissingAfterRegistrationIsDetected() throws Exception {
initWork(); Path repo = Files.createDirectory(root.resolve("runtime"));
var git = new ProcessBuilder("git", "init", repo.toString()).redirectErrorStream(true).start();
git.getInputStream().readAllBytes(); assertThat(git.waitFor()).isZero();
ok("repo", "add", "runtime", "--path", "runtime");
Files.move(repo, root.resolve("moved"));
assertThat(cli("project", "validate")).isEqualTo(4); assertThat(lastOutput).contains("Missing repository");
}
@Test void discussionRepliesKeepHistoryAndResolveOnlyExplicitQuestions() {
initWork();
ok("discussion", "add", "WRK-0001", "--text", "Which renderer?", "--kind", "QUESTION");
ok("discussion", "add", "WRK-0001", "--text", "Canvas", "--kind", "RESPONSE", "--responds-to", "DSC-0001");
ok("work", "context", "WRK-0001", "--format", "json");
assertThat(lastOutput).contains("Which renderer?", "Canvas", "\"outstandingQuestions\" : [ ]");
assertThat(cli("discussion", "add", "WRK-0001", "--text", "Wrong", "--responds-to", "DSC-9999")).isEqualTo(2);
}
@Test @org.junit.jupiter.api.condition.DisabledOnOs(org.junit.jupiter.api.condition.OS.WINDOWS)
void protocolAndWorkSymlinksAreRejected() throws Exception {
initWork(); Path outside = Files.createTempDirectory("aie-link-");
Files.createSymbolicLink(work().resolve("decisions/DEC-0001.md"), outside.resolve("decision.md"));
assertThat(cli("decision", "draft", "WRK-0001", "--title", "Do not escape")).isEqualTo(2);
assertThat(cli("work", "validate", "WRK-0001")).isEqualTo(4);
}
@Test void unknownSchemaFieldsDuplicateKeysAndMalformedYamlFail() throws Exception {
initWork(); Path config = root.resolve(".ai-engineering/ai-engineering.yaml"); String original = Files.readString(config);
for (String corrupt : new String[]{original + "unknownPolicy: true\n", original + "schemaVersion: 2\n", "project: [broken\n"}) {
Files.writeString(config, corrupt); assertThat(cli("project", "validate")).isEqualTo(4);
}
}
@Test void lifecycleIsReversibleAndArtifactsAreWorkLocal() throws Exception {
initWork(); ok("work", "create", "Two");
ok("work", "status", "WRK-0001", "COMPLETED"); ok("work", "status", "WRK-0001", "ACTIVE");
Path source = Files.writeString(root.resolve("result.txt"), "Only first Work\n");
ok("artifact", "add", "WRK-0001", "--file", source.toString(), "--purpose", "First only");
ok("work", "context", "WRK-0002"); assertThat(lastOutput).doesNotContain("First only", "ART-0001");
ok("work", "show", "WRK-0001"); assertThat(lastOutput).contains("ACTIVE");
}
@Test void orphanFilesAndMissingWorkDirectoriesAreDiagnosed() throws Exception {
initWork(); Files.writeString(work().resolve("discussions/orphan.md"), "unreferenced");
Files.delete(work().resolve("runs"));
assertThat(cli("work", "validate", "WRK-0001")).isEqualTo(4);
assertThat(lastOutput).contains("Unreferenced protocol file", "Missing Work directory");
}
}
@@ -0,0 +1,66 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.filesystem.*;
import net.intrepid.aiengineering.project.*;
import net.intrepid.aiengineering.work.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
import java.util.*;
import static org.assertj.core.api.Assertions.*;
class PersistenceTest {
@TempDir Path root;
@Test void atomicCreateNeverOverwritesAndReplacementLeavesNoTemporaryFile() throws Exception {
Path target = root.resolve("state.yaml");
Filespace.write(target, "first", false);
assertThatThrownBy(() -> Filespace.write(target, "second", false)).isInstanceOf(ProtocolException.class);
assertThat(Files.readString(target)).isEqualTo("first");
Filespace.write(target, "replacement", true);
assertThat(Files.readString(target)).isEqualTo("replacement");
try (var files = Files.list(root)) { assertThat(files.map(p -> p.getFileName().toString())).containsExactly("state.yaml"); }
}
@Test void workIdentityReservationSurvivesRemovalAndModelsAreImmutable() throws Exception {
var projects = new ProjectService(); projects.initialize(root, "Test"); var works = new WorkService();
var constraints = new ArrayList<>(List.of("Original"));
var one = works.create(root, "One", "", "Goal", "", constraints, List.of(), List.of(), "human");
constraints.add("Changed"); assertThat(one.constraints()).containsExactly("Original");
assertThatThrownBy(() -> one.constraints().add("Mutate")).isInstanceOf(UnsupportedOperationException.class);
Path removed = root.resolve("removed-work"); Files.move(works.folder(root, one.id()), removed);
var two = works.create(root, "Two", "", "Goal", "", List.of(), List.of(), List.of(), "human");
assertThat(two.id()).isEqualTo("WRK-0002");
}
@Test void omittedAccessIsReadOnlyAndInvalidPolicyIsRejected() {
var config = Documents.parse("""
schemaVersion: 1
project: {id: test, name: Test}
repositories:
- {id: runtime, path: runtime, type: linked-git}
""", ProjectConfig.class);
assertThat(config.repositories().getFirst().access()).isEqualTo(new ProjectConfig.Access(true, false));
assertThatThrownBy(() -> new ProjectConfig.Access(false, true)).isInstanceOf(ProtocolException.class);
}
@Test void numericLifecycleValuesAreRejected() {
var projects = new ProjectService(); projects.initialize(root, "Test"); var works = new WorkService();
var work = works.create(root, "One", "", "Goal", "", List.of(), List.of(), List.of(), "human");
String invalid = Documents.yaml(work).replaceAll("(?m)^status:.*$", "status: 0");
assertThatThrownBy(() -> Documents.parse(invalid, Work.class)).isInstanceOf(ProtocolException.class);
}
@Test void realGitSubmoduleCanBeRegisteredWithoutReconfiguration() throws Exception {
var projects = new ProjectService(); projects.initialize(root, "Test");
Path upstream = Files.createTempDirectory("aie-upstream-");
git("init", upstream.toString());
git("-C", upstream.toString(), "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "--allow-empty", "-m", "fixture");
git("init", root.toString());
git("-C", root.toString(), "-c", "protocol.file.allow=always", "submodule", "add", upstream.toString(), "runtime");
Path modules = root.resolve(".gitmodules"); byte[] before = Files.readAllBytes(modules);
projects.addRepository(root, new ProjectConfig.Repository("runtime", "runtime", "git-submodule", "rust", null, null));
projects.validate(root);
assertThat(Files.readAllBytes(modules)).isEqualTo(before);
}
private static void git(String... args) throws Exception {
var command = new ArrayList<>(List.of("git")); command.addAll(List.of(args));
var process = new ProcessBuilder(command).redirectErrorStream(true).start();
String out = new String(process.getInputStream().readAllBytes()); assertThat(process.waitFor()).as(out).isZero();
}
}
@@ -0,0 +1,47 @@
package net.intrepid.aiengineering;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
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. */
class ProcessContinuityTest {
@TempDir Path root;
private String cli(String... args) throws Exception {
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");
try {
var process = new ProcessBuilder(command).directory(root.toFile()).redirectErrorStream(true).redirectOutput(log.toFile()).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); }
}
@Test void independentJvmProcessesReconstructMultiRepositoryWork() throws Exception {
cli("init", "--name", "Continuity Experiment");
for (String repo : List.of("runtime", "studio")) {
Path path = Files.createDirectory(root.resolve(repo));
var git = new ProcessBuilder("git", "init", path.toString()).redirectErrorStream(true).start();
git.getInputStream().readAllBytes(); assertThat(git.waitFor()).isZero();
var commit = new ProcessBuilder("git", "-C", path.toString(), "-c", "user.name=Fixture", "-c",
"user.email=fixture@example.invalid", "commit", "--allow-empty", "-m", "fixture").redirectErrorStream(true).start();
commit.getInputStream().readAllBytes(); assertThat(commit.waitFor()).isZero();
cli("repo", "add", repo, "--path", repo);
}
cli("work", "create", "Improve scene editor", "--repo", "runtime", "--repo", "studio", "--goal", "Continue across agents");
cli("discussion", "add", "WRK-0001", "--text", "Evaluate Canvas rendering", "--author", "agent-a");
cli("decision", "draft", "WRK-0001", "--title", "Use layered Canvas");
Path evidence = Files.writeString(root.resolve("result.txt"), "Observed rendering result\n");
cli("artifact", "add", "WRK-0001", "--file", evidence.toString(), "--purpose", "Rendering experiment");
String first = cli("work", "context", "WRK-0001", "--format", "json");
assertThat(cli("work", "context", "WRK-0001", "--format", "json")).isEqualTo(first)
.contains("agent-a", "runtime", "studio", "sha256", "DRAFT", "Continue across agents");
assertThat(cli("project", "validate", "--format", "json")).contains("\"valid\" : true");
}
}
@@ -0,0 +1,92 @@
package net.intrepid.aiengineering;
import net.intrepid.aiengineering.cli.EngineeringCli;
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 ProtocolIntegrationTest {
@TempDir Path root;
record Result(int code, String out, String err) {}
Result run(Path cwd, String... args) {
var out = new StringWriter(); var err = new StringWriter();
int code = new EngineeringCli(cwd).execute(new PrintWriter(out), new PrintWriter(err), args);
return new Result(code, out.toString(), err.toString());
}
Result ok(String... args) {
var r = run(root, args);
assertThat(r.code()).as(r.err()).isZero(); return r;
}
void init() { ok("init", "--name", "Test Project"); }
void repository(String name) throws Exception {
Path path = Files.createDirectory(root.resolve(name));
var process = new ProcessBuilder("git", "init", path.toString()).redirectErrorStream(true).start();
process.getInputStream().readAllBytes(); assertThat(process.waitFor()).isZero();
ok("repo", "add", name, "--path", name);
}
@Test void portableMultiRepositoryContinuity() throws Exception {
init(); repository("runtime"); repository("studio");
ok("work", "create", "Improve scene editor", "--goal", "Portable rendering", "--repo", "runtime", "--repo", "studio",
"--constraint", "No web server", "--acceptance", "Context reloads");
ok("discussion", "add", "WRK-0001", "--kind", "QUESTION", "--text", "Evaluate Canvas rendering?");
ok("discussion", "add", "WRK-0001", "--kind", "CONCLUSION", "--text", "Evaluate layered Canvas first");
ok("decision", "draft", "WRK-0001", "--title", "Use layered Canvas");
Path evidence = Files.writeString(root.resolve("evidence.txt"), "Rendering experiment: 60 fps\n");
ok("artifact", "add", "WRK-0001", "--file", evidence.toString(), "--purpose", "Rendering evidence");
String before = ok("work", "context", "WRK-0001").out();
Path nested = Files.createDirectories(root.resolve("studio/src/editor"));
var fresh = run(nested, "work", "context", "WRK-0001");
assertThat(fresh.code()).as(fresh.err()).isZero();
assertThat(fresh.out()).isEqualTo(before).contains("Portable rendering", "No web server", "Context reloads",
"Evaluate Canvas rendering?", "Use layered Canvas", "DRAFT", "Rendering evidence", "runtime", "studio", "OPEN");
assertThat(ok("work", "context", "WRK-0001", "--format", "json").out()).contains("\"schemaVersion\"", "sha256");
ok("project", "validate"); ok("work", "validate", "WRK-0001");
assertThat(Files.exists(root.resolve(".git"))).isFalse();
}
@Test void independentWorksAndDeterministicExports() {
init(); ok("work", "create", "One"); ok("work", "create", "Two");
ok("discussion", "add", "WRK-0001", "--text", "Only one");
assertThat(ok("work", "list", "--format", "json").out()).contains("WRK-0001", "WRK-0002");
assertThat(ok("work", "context", "WRK-0002").out()).doesNotContain("Only one");
assertThat(ok("work", "context", "WRK-0001").out()).isEqualTo(ok("work", "context", "WRK-0001").out());
}
@Test void invalidIdentifiersMissingResourcesAndNoOverwrite() throws Exception {
init();
assertThat(run(root, "init", "--name", "Again").code()).isEqualTo(2);
assertThat(run(root, "work", "show", "../../escape").code()).isEqualTo(2);
assertThat(run(root, "work", "show", "WRK-9999").code()).isEqualTo(3);
assertThat(run(root, "repo", "add", "missing", "--path", "missing").code()).isEqualTo(3);
assertThat(run(root, "repo", "add", "escape", "--path", "../escape").code()).isEqualTo(2);
org.junit.jupiter.api.Assumptions.assumeFalse(System.getProperty("os.name").startsWith("Windows"), "Symlink fixtures need OS support");
Path outside = Files.createTempDirectory("aie-outside-");
Files.createSymbolicLink(root.resolve("escape"), outside);
assertThat(run(root, "repo", "add", "escape", "--path", "escape").code()).isEqualTo(2);
}
@Test void validationDetectsMissingDecisionArtifactAndDuplicateWork() throws Exception {
init(); ok("work", "create", "One");
ok("decision", "draft", "WRK-0001", "--title", "Draft");
Path work = root.resolve(".ai-engineering/works/WRK-0001-one");
Files.delete(work.resolve("decisions/DEC-0001.md"));
assertThat(run(root, "work", "validate", "WRK-0001").code()).isEqualTo(4);
Files.createDirectory(root.resolve(".ai-engineering/works/WRK-0001-copy"));
Files.copy(work.resolve("work.md"), root.resolve(".ai-engineering/works/WRK-0001-copy/work.md"));
assertThat(run(root, "project", "validate").code()).isEqualTo(4);
}
@Test void invalidConfigurationIsDiagnosed() throws Exception {
init(); Files.writeString(root.resolve(".ai-engineering/ai-engineering.yaml"), "schemaVersion: 999\n");
assertThat(run(root, "project", "validate").code()).isEqualTo(4);
}
@Test void cliSmokeAndHelpForEveryCommand() {
assertThat(ok("--version").out()).isEqualTo("ai-engineering 0.1.0\n");
for (String command : new String[]{"", "init", "project", "project show", "project validate", "repo", "repo add", "repo list",
"work", "work create", "work list", "work show", "work validate", "work context", "discussion", "discussion add",
"decision", "decision draft", "artifact", "artifact add"}) {
var args = new java.util.ArrayList<String>();
if (!command.isEmpty()) args.addAll(java.util.List.of(command.split(" ")));
args.add("--help"); assertThat(ok(args.toArray(String[]::new)).out()).contains("Usage:");
}
assertThat(run(root, "--unknown").code()).isEqualTo(2);
}
}