From 202a88f6535470574cccec0936a951b750806efc Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 13:43:31 +0530 Subject: [PATCH 01/16] feat(demo): scaffold spring-ai-engram-cloud-demo module --- .../spring-ai-engram-cloud-demo/.gitignore | 5 + examples/spring-ai-engram-cloud-demo/pom.xml | 102 ++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/.gitignore create mode 100644 examples/spring-ai-engram-cloud-demo/pom.xml diff --git a/examples/spring-ai-engram-cloud-demo/.gitignore b/examples/spring-ai-engram-cloud-demo/.gitignore new file mode 100644 index 0000000..2d70269 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/.gitignore @@ -0,0 +1,5 @@ +target/ +.env +.idea/ +*.iml +.vscode/ diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml new file mode 100644 index 0000000..f5e7cd3 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + dev.jamjet.examples + spring-ai-engram-cloud-demo + 1.0.0-SNAPSHOT + jar + + Spring AI + Engram + JamJet Cloud Demo + Reference demo: Spring AI agent with durable Engram MCP memory, observed by JamJet Cloud + + + UTF-8 + 21 + 3.3.5 + 1.0.0 + 0.2.0 + 3.9.1 + 1.20.4 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.ai + spring-ai-starter-model-openai + + + org.springframework.ai + spring-ai-starter-mcp-client + + + dev.jamjet + jamjet-cloud-spring-boot-starter + ${jamjet-cloud.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.wiremock + wiremock-standalone + ${wiremock.version} + test + + + org.testcontainers + testcontainers + test + + + org.testcontainers + junit-jupiter + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + + From 84b7c5114301eab0628b7ac3b1be9bb2a3785bea Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 13:49:05 +0530 Subject: [PATCH 02/16] feat(demo): add Maven wrapper to spring-ai-engram-cloud-demo --- .../.mvn/wrapper/maven-wrapper.properties | 3 + examples/spring-ai-engram-cloud-demo/mvnw | 295 ++++++++++++++++++ examples/spring-ai-engram-cloud-demo/mvnw.cmd | 189 +++++++++++ 3 files changed, 487 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/.mvn/wrapper/maven-wrapper.properties create mode 100755 examples/spring-ai-engram-cloud-demo/mvnw create mode 100644 examples/spring-ai-engram-cloud-demo/mvnw.cmd diff --git a/examples/spring-ai-engram-cloud-demo/.mvn/wrapper/maven-wrapper.properties b/examples/spring-ai-engram-cloud-demo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/examples/spring-ai-engram-cloud-demo/mvnw b/examples/spring-ai-engram-cloud-demo/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/examples/spring-ai-engram-cloud-demo/mvnw.cmd b/examples/spring-ai-engram-cloud-demo/mvnw.cmd new file mode 100644 index 0000000..5761d94 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" From 1c21ef8a6101a6a4df045dd9cebeaeea1f11c43e Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 14:01:00 +0530 Subject: [PATCH 03/16] feat(demo): add Engram docker-compose + .env.example --- .../spring-ai-engram-cloud-demo/.env.example | 8 ++++++++ .../docker-compose.yml | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/.env.example create mode 100644 examples/spring-ai-engram-cloud-demo/docker-compose.yml diff --git a/examples/spring-ai-engram-cloud-demo/.env.example b/examples/spring-ai-engram-cloud-demo/.env.example new file mode 100644 index 0000000..4603898 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/.env.example @@ -0,0 +1,8 @@ +# Sign up at https://platform.openai.com/api-keys to get an OpenAI key. +OPENAI_API_KEY=sk-... + +# Sign up at https://cloud.jamjet.dev, create a project, and copy the API key. +JAMJET_API_KEY=jk_... + +# Optional — defaults to the public hosted JamJet Cloud. +# JAMJET_API_URL=https://api.jamjet.dev diff --git a/examples/spring-ai-engram-cloud-demo/docker-compose.yml b/examples/spring-ai-engram-cloud-demo/docker-compose.yml new file mode 100644 index 0000000..2764dd0 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/docker-compose.yml @@ -0,0 +1,16 @@ +services: + engram: + image: ghcr.io/jamjet-labs/engram-server:0.5.0 + container_name: engram-demo + ports: + - "127.0.0.1:8001:8001" + environment: + - ENGRAM_MODE=rest + - ENGRAM_PORT=8001 + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://localhost:8001/health"] + interval: 2s + timeout: 1s + retries: 15 + start_period: 5s + restart: unless-stopped From a40cedd3e42e6e8b50850aa438cdf5908b124627 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 14:37:30 +0530 Subject: [PATCH 04/16] Revert "feat(demo): add Engram docker-compose + .env.example" This reverts commit 1c21ef8a6101a6a4df045dd9cebeaeea1f11c43e. --- .../spring-ai-engram-cloud-demo/.env.example | 8 -------- .../docker-compose.yml | 16 ---------------- 2 files changed, 24 deletions(-) delete mode 100644 examples/spring-ai-engram-cloud-demo/.env.example delete mode 100644 examples/spring-ai-engram-cloud-demo/docker-compose.yml diff --git a/examples/spring-ai-engram-cloud-demo/.env.example b/examples/spring-ai-engram-cloud-demo/.env.example deleted file mode 100644 index 4603898..0000000 --- a/examples/spring-ai-engram-cloud-demo/.env.example +++ /dev/null @@ -1,8 +0,0 @@ -# Sign up at https://platform.openai.com/api-keys to get an OpenAI key. -OPENAI_API_KEY=sk-... - -# Sign up at https://cloud.jamjet.dev, create a project, and copy the API key. -JAMJET_API_KEY=jk_... - -# Optional — defaults to the public hosted JamJet Cloud. -# JAMJET_API_URL=https://api.jamjet.dev diff --git a/examples/spring-ai-engram-cloud-demo/docker-compose.yml b/examples/spring-ai-engram-cloud-demo/docker-compose.yml deleted file mode 100644 index 2764dd0..0000000 --- a/examples/spring-ai-engram-cloud-demo/docker-compose.yml +++ /dev/null @@ -1,16 +0,0 @@ -services: - engram: - image: ghcr.io/jamjet-labs/engram-server:0.5.0 - container_name: engram-demo - ports: - - "127.0.0.1:8001:8001" - environment: - - ENGRAM_MODE=rest - - ENGRAM_PORT=8001 - healthcheck: - test: ["CMD", "wget", "-q", "--spider", "http://localhost:8001/health"] - interval: 2s - timeout: 1s - retries: 15 - start_period: 5s - restart: unless-stopped From 86d42b9fa8909fe450b1494c16da5b96f35b2174 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 15:11:18 +0530 Subject: [PATCH 05/16] feat(demo): use engram-spring-boot-starter instead of Spring AI MCP client --- examples/spring-ai-engram-cloud-demo/pom.xml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml index f5e7cd3..25dc23f 100644 --- a/examples/spring-ai-engram-cloud-demo/pom.xml +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -18,6 +18,7 @@ 3.3.5 1.0.0 0.2.0 + 0.2.0 3.9.1 1.20.4 @@ -58,8 +59,9 @@ spring-ai-starter-model-openai - org.springframework.ai - spring-ai-starter-mcp-client + dev.jamjet + engram-spring-boot-starter + ${jamjet-engram.version} dev.jamjet From 8a01f0ed0d23837f131f6f008f5bd24977cf1edb Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 15:42:23 +0530 Subject: [PATCH 06/16] feat(demo): Engram (Rust 0.5.0) docker-compose + .env.example Deviations from original spec (confirmed via CLI inspection): - Added ENGRAM_MODE=rest (default is mcp/stdio; HTTP requires explicit opt-in) - Health endpoint is /health not /healthz (404 confirmed on /healthz) - Added ENGRAM_EMBEDDING_PROVIDER=mock (avoids Ollama dependency for embeddings) - Removed explicit command/port args; port 9090 is already the REST default - Added named volume engram-data for SQLite persistence across restarts - Recall query param is q= not query= (documented for Task 7 EngramClient wiring) - mock LLM provider returns zero facts by design (logged warning from binary) --- .../spring-ai-engram-cloud-demo/.env.example | 8 +++++++ .../docker-compose.yml | 24 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/.env.example create mode 100644 examples/spring-ai-engram-cloud-demo/docker-compose.yml diff --git a/examples/spring-ai-engram-cloud-demo/.env.example b/examples/spring-ai-engram-cloud-demo/.env.example new file mode 100644 index 0000000..4603898 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/.env.example @@ -0,0 +1,8 @@ +# Sign up at https://platform.openai.com/api-keys to get an OpenAI key. +OPENAI_API_KEY=sk-... + +# Sign up at https://cloud.jamjet.dev, create a project, and copy the API key. +JAMJET_API_KEY=jk_... + +# Optional — defaults to the public hosted JamJet Cloud. +# JAMJET_API_URL=https://api.jamjet.dev diff --git a/examples/spring-ai-engram-cloud-demo/docker-compose.yml b/examples/spring-ai-engram-cloud-demo/docker-compose.yml new file mode 100644 index 0000000..a488886 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/docker-compose.yml @@ -0,0 +1,24 @@ +services: + engram: + image: ghcr.io/jamjet-labs/engram-server:0.5.0 + container_name: engram-demo + # No explicit command — all configuration is via environment variables. + # "serve" is the default entrypoint; mode=rest and port=9090 are set below. + ports: + - "127.0.0.1:9090:9090" # loopback-only — do not expose Engram on the network + environment: + - ENGRAM_MODE=rest # default is "mcp" (stdio); must be "rest" for HTTP + - ENGRAM_LLM_PROVIDER=mock # no LLM key needed; mock returns empty facts (demo/dev only) + - ENGRAM_EMBEDDING_PROVIDER=mock # no Ollama needed; mock embeddings (768d, deterministic) + volumes: + - engram-data:/data # ENGRAM_DB_PATH defaults to /data/engram.db inside the image + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://localhost:9090/health"] + interval: 2s + timeout: 1s + retries: 15 + start_period: 5s + restart: unless-stopped + +volumes: + engram-data: From 83c8f9bc029acf34404a8b0bd052ca819dc0dff3 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 15:45:14 +0530 Subject: [PATCH 07/16] feat(demo): switch Engram to openai-compatible LLM provider so fact extraction works --- examples/spring-ai-engram-cloud-demo/docker-compose.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/spring-ai-engram-cloud-demo/docker-compose.yml b/examples/spring-ai-engram-cloud-demo/docker-compose.yml index a488886..c61adef 100644 --- a/examples/spring-ai-engram-cloud-demo/docker-compose.yml +++ b/examples/spring-ai-engram-cloud-demo/docker-compose.yml @@ -7,9 +7,11 @@ services: ports: - "127.0.0.1:9090:9090" # loopback-only — do not expose Engram on the network environment: - - ENGRAM_MODE=rest # default is "mcp" (stdio); must be "rest" for HTTP - - ENGRAM_LLM_PROVIDER=mock # no LLM key needed; mock returns empty facts (demo/dev only) - - ENGRAM_EMBEDDING_PROVIDER=mock # no Ollama needed; mock embeddings (768d, deterministic) + - ENGRAM_MODE=rest # default is "mcp" (stdio); must be "rest" for HTTP + - ENGRAM_LLM_PROVIDER=openai-compatible # real fact extraction so the demo's memory actually works + - ENGRAM_OPENAI_BASE_URL=https://api.openai.com/v1 + - OPENAI_API_KEY=${OPENAI_API_KEY:?OPENAI_API_KEY required for Engram fact extraction; copy .env.example to .env and paste your key} + - ENGRAM_EMBEDDING_PROVIDER=mock # mock embeddings (768d, deterministic) — fine for a 3-fact demo without an Ollama prereq volumes: - engram-data:/data # ENGRAM_DB_PATH defaults to /data/engram.db inside the image healthcheck: From f0da8831d7e5bd8e30319d91a42dc4c4a978b398 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 15:55:34 +0530 Subject: [PATCH 08/16] feat(demo): PreflightCheck validates required env vars at startup --- .../startup/PreflightCheck.java | 59 +++++++++++++++++++ .../springaiengram/PreflightCheckTest.java | 53 +++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java create mode 100644 examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java new file mode 100644 index 0000000..e2c759c --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java @@ -0,0 +1,59 @@ +package dev.jamjet.demo.springaiengram.startup; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Map; + +@Component +@Profile("!test") +public class PreflightCheck implements ApplicationRunner { + + private final Map env; + private final String engramHealthUrl; + + public PreflightCheck(@Value("${app.engram.health-url:http://127.0.0.1:9090/health}") String engramHealthUrl) { + this(System.getenv(), engramHealthUrl); + } + + // Test constructor. + public PreflightCheck(Map env, String engramHealthUrl) { + this.env = env; + this.engramHealthUrl = engramHealthUrl; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + validateEnv(); + waitForEngram(); + } + + public void validateEnv() { + if (isBlank(env.get("OPENAI_API_KEY"))) { + throw new IllegalStateException( + "OPENAI_API_KEY is not set. Get a key at https://platform.openai.com/api-keys " + + "and put it in your .env file."); + } + if (isBlank(env.get("JAMJET_API_KEY"))) { + throw new IllegalStateException( + "JAMJET_API_KEY is not set. Sign up at https://cloud.jamjet.dev, create a project, " + + "and put the API key in your .env file."); + } + } + + void waitForEngram() { + // Implementation in Task 5. + } + + private boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java new file mode 100644 index 0000000..862b470 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java @@ -0,0 +1,53 @@ +package dev.jamjet.demo.springaiengram; + +import dev.jamjet.demo.springaiengram.startup.PreflightCheck; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +class PreflightCheckTest { + + @Test + void rejectsMissingOpenAiKey() { + PreflightCheck check = new PreflightCheck( + Map.of("JAMJET_API_KEY", "jk_test"), + "http://localhost:65535/health" // unreachable; we shouldn't get past env check + ); + + Throwable thrown = catchThrowable(() -> check.validateEnv()); + + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OPENAI_API_KEY") + .hasMessageContaining("platform.openai.com"); + } + + @Test + void rejectsMissingJamjetKey() { + PreflightCheck check = new PreflightCheck( + Map.of("OPENAI_API_KEY", "sk-test"), + "http://localhost:65535/health" + ); + + Throwable thrown = catchThrowable(() -> check.validateEnv()); + + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("JAMJET_API_KEY") + .hasMessageContaining("cloud.jamjet.dev"); + } + + @Test + void acceptsBothKeysPresent() { + PreflightCheck check = new PreflightCheck( + Map.of("OPENAI_API_KEY", "sk-test", "JAMJET_API_KEY", "jk_test"), + "http://localhost:65535/health" + ); + + // No throw expected. + check.validateEnv(); + } +} From 8070725e2a3a46732d8f268c312beb3b7fa0dc32 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 17:22:19 +0530 Subject: [PATCH 09/16] feat(demo): PreflightCheck polls Engram /health with timeout --- .../startup/PreflightCheck.java | 37 ++++++++++++++++++- .../springaiengram/PreflightCheckTest.java | 33 +++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java index e2c759c..c97c1ba 100644 --- a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java @@ -49,8 +49,41 @@ public void validateEnv() { } } - void waitForEngram() { - // Implementation in Task 5. + public void waitForEngram() { + waitForEngramWithTimeout(Duration.ofSeconds(30)); + } + + public void waitForEngramWithTimeout(Duration timeout) { + HttpClient client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(2)) + .build(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(engramHealthUrl)) + .timeout(Duration.ofSeconds(2)) + .GET() + .build(); + + long deadlineMs = System.currentTimeMillis() + timeout.toMillis(); + while (System.currentTimeMillis() < deadlineMs) { + try { + HttpResponse resp = client.send(request, HttpResponse.BodyHandlers.discarding()); + if (resp.statusCode() == 200) { + return; + } + } catch (Exception ignored) { + // retry until deadline + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for Engram", e); + } + } + + throw new IllegalStateException( + "Engram is not reachable at " + engramHealthUrl + ". " + + "Run `docker compose up -d` first."); } private boolean isBlank(String value) { diff --git a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java index 862b470..ff0e409 100644 --- a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java +++ b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/PreflightCheckTest.java @@ -50,4 +50,37 @@ void acceptsBothKeysPresent() { // No throw expected. check.validateEnv(); } + + @Test + void waitsForEngramHealth_succeedsImmediately() { + com.github.tomakehurst.wiremock.WireMockServer wm = + new com.github.tomakehurst.wiremock.WireMockServer(0); + wm.start(); + wm.stubFor(com.github.tomakehurst.wiremock.client.WireMock.get("/health") + .willReturn(com.github.tomakehurst.wiremock.client.WireMock.ok())); + try { + PreflightCheck check = new PreflightCheck( + Map.of("OPENAI_API_KEY", "sk", "JAMJET_API_KEY", "jk"), + wm.baseUrl() + "/health" + ); + check.waitForEngram(); // should not throw + } finally { + wm.stop(); + } + } + + @Test + void waitsForEngramHealth_timesOut() { + PreflightCheck check = new PreflightCheck( + Map.of("OPENAI_API_KEY", "sk", "JAMJET_API_KEY", "jk"), + "http://127.0.0.1:65535/health" // nothing listening + ); + + Throwable thrown = catchThrowable(() -> check.waitForEngramWithTimeout(java.time.Duration.ofSeconds(2))); + + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Engram") + .hasMessageContaining("docker compose up"); + } } From 8142ed2cfac478f6c01791c375b39297b81bea3b Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 17:45:07 +0530 Subject: [PATCH 10/16] feat(demo): DemoApplication + application.yml --- .../demo/springaiengram/DemoApplication.java | 11 +++++++ .../src/main/resources/application.yml | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/DemoApplication.java create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/resources/application.yml diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/DemoApplication.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/DemoApplication.java new file mode 100644 index 0000000..5179e97 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/DemoApplication.java @@ -0,0 +1,11 @@ +package dev.jamjet.demo.springaiengram; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/examples/spring-ai-engram-cloud-demo/src/main/resources/application.yml b/examples/spring-ai-engram-cloud-demo/src/main/resources/application.yml new file mode 100644 index 0000000..5c6ddcc --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/resources/application.yml @@ -0,0 +1,31 @@ +server: + address: 127.0.0.1 + port: 8080 + +spring: + application: + name: spring-ai-engram-cloud-demo + ai: + openai: + api-key: ${OPENAI_API_KEY} + chat: + options: + model: gpt-4o-mini + +# Engram Spring Boot starter — autoconfigures EngramClient bound to engram.base-url +engram: + base-url: ${ENGRAM_BASE_URL:http://127.0.0.1:9090} + +jamjet: + cloud: + api-key: ${JAMJET_API_KEY} + api-url: ${JAMJET_API_URL:https://api.jamjet.dev} + +app: + engram: + health-url: ${ENGRAM_BASE_URL:http://127.0.0.1:9090}/health + +logging: + level: + org.springframework.ai: INFO + dev.jamjet: INFO From e3f71884d0fdccbd080b10d8b71ea497a149cc0b Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 18:09:17 +0530 Subject: [PATCH 11/16] feat(demo): MemoryTools + MemoryAgent + ChatController --- .../demo/springaiengram/ChatController.java | 24 ++++++++++++ .../demo/springaiengram/MemoryAgent.java | 30 +++++++++++++++ .../demo/springaiengram/MemoryTools.java | 37 +++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/ChatController.java create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryAgent.java create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryTools.java diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/ChatController.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/ChatController.java new file mode 100644 index 0000000..3017a0a --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/ChatController.java @@ -0,0 +1,24 @@ +package dev.jamjet.demo.springaiengram; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ChatController { + + private final MemoryAgent agent; + + public ChatController(MemoryAgent agent) { + this.agent = agent; + } + + @PostMapping("/chat") + public ChatResponse chat(@RequestParam String session, @RequestBody String message) { + String reply = agent.chat(session, message); + return new ChatResponse(session, reply); + } + + public record ChatResponse(String session, String reply) {} +} diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryAgent.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryAgent.java new file mode 100644 index 0000000..13001f8 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryAgent.java @@ -0,0 +1,30 @@ +package dev.jamjet.demo.springaiengram; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.stereotype.Service; + +@Service +public class MemoryAgent { + + private final ChatClient chatClient; + + public MemoryAgent(ChatClient.Builder chatClientBuilder, MemoryTools memoryTools) { + this.chatClient = chatClientBuilder + .defaultSystem(""" + You are a helpful assistant with durable memory backed by Engram. + When the user shares a fact about themselves, call rememberFact to store it. + When the user asks a question that may have been answered before, call recallFacts first. + If recallFacts returns nothing relevant, say "I don't know yet" — do not guess. + Always pass the session id (provided in the user message header [session=...]) as the userId argument to both tools. + """) + .defaultTools(memoryTools) + .build(); + } + + public String chat(String sessionId, String userMessage) { + return chatClient.prompt() + .user("[session=" + sessionId + "] " + userMessage) + .call() + .content(); + } +} diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryTools.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryTools.java new file mode 100644 index 0000000..a2370b0 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/MemoryTools.java @@ -0,0 +1,37 @@ +package dev.jamjet.demo.springaiengram; + +import dev.jamjet.engram.EngramClient; +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +@Component +public class MemoryTools { + + private static final String DEMO_ORG = "demo"; + + private final EngramClient engram; + + public MemoryTools(EngramClient engram) { + this.engram = engram; + } + + @Tool(description = "Store a fact about the user in durable memory. Use when the user shares preferences or personal details.") + public String rememberFact( + @ToolParam(description = "The fact to remember, in the user's own words") String text, + @ToolParam(description = "The user identifier — pass through the session id from the chat request") String userId) { + var messages = List.of(Map.of("role", "user", "content", text)); + var result = engram.add(messages, userId, DEMO_ORG, userId); + return "Stored fact for user " + userId + ": " + result; + } + + @Tool(description = "Recall facts previously stored about the user. Returns the top matches; use when answering a question that may depend on prior context.") + public List> recallFacts( + @ToolParam(description = "Natural-language query describing what you're looking for") String query, + @ToolParam(description = "The user identifier — pass through the session id from the chat request") String userId) { + return engram.recall(query, userId, DEMO_ORG, 5); + } +} From 402dc1fe10b38969a110545c637bf74f42b54553 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 21:16:34 +0530 Subject: [PATCH 12/16] test(demo): integration test with WireMock + Testcontainers Engram MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DemoIntegrationTest: WireMock stubs OpenAI chat completions returning "Acme"; Testcontainers runs real Engram 0.5.0 with mock LLM provider; @SpringBootTest asserts the /chat endpoint returns the stubbed reply. Three companion fixes required to make the test pass: - Upgraded Testcontainers 1.20.4 → 1.21.3 (docker-java 3.4.2) and moved TC BOM before spring-boot-dependencies so the version wins. - Added api.version=1.41 as a Surefire JVM property; TC ≤1.21.x falls back to docker-java API 1.32 when UNKNOWN_VERSION is detected, and OrbStack 2.x dropped support for API < 1.40. - Enabled -parameters compiler flag so Spring MVC resolves @RequestParam names at runtime without relying on debug info. - Excluded JamjetCloudAutoConfiguration (0.2.0 references langchain4j which is not on the test classpath; guards the @SpringBootTest context). --- examples/spring-ai-engram-cloud-demo/pom.xml | 46 +++++++-- .../springaiengram/DemoIntegrationTest.java | 98 +++++++++++++++++++ 2 files changed, 136 insertions(+), 8 deletions(-) create mode 100644 examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml index 25dc23f..cf67d7d 100644 --- a/examples/spring-ai-engram-cloud-demo/pom.xml +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -20,11 +20,19 @@ 0.2.0 0.2.0 3.9.1 - 1.20.4 + 1.21.3 + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + org.springframework.boot spring-boot-dependencies @@ -39,13 +47,6 @@ pom import - - org.testcontainers - testcontainers-bom - ${testcontainers.version} - pom - import - @@ -99,6 +100,35 @@ spring-boot-maven-plugin ${spring-boot.version} + + + org.apache.maven.plugins + maven-compiler-plugin + + + -parameters + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + 1.41 + + + diff --git a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java new file mode 100644 index 0000000..19712a0 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java @@ -0,0 +1,98 @@ +package dev.jamjet.demo.springaiengram; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import dev.jamjet.cloud.spring.JamjetCloudAutoConfiguration; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.web.client.RestTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +import static org.assertj.core.api.Assertions.assertThat; + +@ActiveProfiles("test") +@Testcontainers +// JamjetCloudAutoConfiguration 0.2.0 references langchain4j which is not on the test classpath; +// exclude it to avoid ClassNotFoundException during condition processing. +@EnableAutoConfiguration(exclude = JamjetCloudAutoConfiguration.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class DemoIntegrationTest { + + static WireMockServer wireMock; + + @Container + static GenericContainer engram = new GenericContainer<>( + DockerImageName.parse("ghcr.io/jamjet-labs/engram-server:0.5.0")) + .withExposedPorts(9090) + .withEnv("ENGRAM_MODE", "rest") + .withEnv("ENGRAM_LLM_PROVIDER", "mock") + .withEnv("ENGRAM_EMBEDDING_PROVIDER", "mock") + .waitingFor(Wait.forHttp("/health").forStatusCode(200)); + + @BeforeAll + static void startWireMock() { + wireMock = new WireMockServer(0); + wireMock.start(); + // Stub a single OpenAI chat completion that returns "Acme". + wireMock.stubFor(WireMock.post(WireMock.urlMatching("/v1/chat/completions.*")) + .willReturn(WireMock.okJson(""" + { + "id": "chatcmpl-test", + "object": "chat.completion", + "model": "gpt-4o-mini", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "Acme"}, + "finish_reason": "stop" + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11} + } + """))); + } + + @AfterAll + static void stopWireMock() { + if (wireMock != null) wireMock.stop(); + } + + @DynamicPropertySource + static void overrideProps(DynamicPropertyRegistry registry) { + registry.add("spring.ai.openai.base-url", () -> wireMock.baseUrl()); + registry.add("spring.ai.openai.api-key", () -> "sk-test"); + registry.add("engram.base-url", + () -> "http://" + engram.getHost() + ":" + engram.getMappedPort(9090)); + registry.add("jamjet.cloud.api-key", () -> "jk_test"); + registry.add("jamjet.cloud.api-url", () -> "http://localhost:1"); + registry.add("app.engram.health-url", + () -> "http://" + engram.getHost() + ":" + engram.getMappedPort(9090) + "/health"); + } + + @LocalServerPort + int port; + + @Autowired + RestTemplateBuilder restTemplateBuilder; + + @Test + void chatEndpointReturnsAgentReply() { + RestTemplate rt = restTemplateBuilder.build(); + String body = rt.postForObject( + "http://127.0.0.1:" + port + "/chat?session=alice", + "Where do I work?", + String.class); + assertThat(body).contains("Acme"); + } +} From 76399b8fdc58c3ed50074dd4ce10d7c0a754ae90 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 21:42:04 +0530 Subject: [PATCH 13/16] docs(demo): README for spring-ai-engram-cloud-demo --- .../spring-ai-engram-cloud-demo/README.md | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 examples/spring-ai-engram-cloud-demo/README.md diff --git a/examples/spring-ai-engram-cloud-demo/README.md b/examples/spring-ai-engram-cloud-demo/README.md new file mode 100644 index 0000000..ab566e1 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/README.md @@ -0,0 +1,138 @@ +# Spring AI + Engram + JamJet Cloud Demo + +A multi-turn chat agent that **remembers facts across calls** via [Engram](https://github.com/jamjet-labs/jamjet/tree/main/runtime/engram-server) and is **observed end-to-end** by [JamJet Cloud](https://cloud.jamjet.dev) — drop in three Spring Boot starters, get durable memory + cloud observability for free. + +## What this demo shows + +- **Spring AI 1.0** chat agent using OpenAI for inference +- **`dev.jamjet:engram-spring-boot-starter`** autoconfigures `EngramClient` so the agent's `@Tool` methods can record + recall facts against a real Engram server +- **`dev.jamjet:jamjet-cloud-spring-boot-starter`** auto-instruments every chat call + tool span — no code changes +- **Cross-platform run flow** — works on macOS, Linux, and Windows with the same `mvnw` + `docker compose` commands + +## How it's wired + +``` +User → POST /chat?session=alice ──→ Spring AI ChatClient + │ + ├─→ OpenAI chat completion + │ + └─→ @Tool methods (rememberFact / recallFacts) + │ + └─→ EngramClient (autoconfigured) + │ + └─→ Engram REST API (Docker) +``` + +JamJet Cloud's starter watches the whole flow via Spring AI's Micrometer Observation hooks and ships traces + cost rollups to the dashboard. **Zero observability code in your demo.** + +## Prerequisites + +- **Java 21+** (`--release 21`; Java 23 also works) +- **Docker Desktop** (or any Docker engine) — for the Engram sidecar +- **An OpenAI API key** — sign up at [platform.openai.com](https://platform.openai.com/api-keys) +- **A JamJet Cloud project** — sign up at [cloud.jamjet.dev](https://cloud.jamjet.dev), create a project, copy the API key + +> **Cost note:** The OpenAI key is used twice per chat turn — once by Spring AI for the chat completion, and once by Engram for fact extraction (the LLM that turns "I prefer espresso" into a structured fact). Both calls use `gpt-4o-mini` by default. + +## Run it + +```bash +git clone https://github.com/jamjet-labs/jamjet-runtime-java +cd jamjet-runtime-java/examples/spring-ai-engram-cloud-demo + +cp .env.example .env # Windows: copy .env.example .env +# Edit .env — paste your OPENAI_API_KEY and JAMJET_API_KEY + +docker compose up -d # boots Engram on 127.0.0.1:9090 +./mvnw spring-boot:run # Windows: mvnw.cmd spring-boot:run +``` + +The app starts on `127.0.0.1:8080`. `PreflightCheck` validates both env vars and waits for Engram's `/health` endpoint before the server accepts requests — if either is missing or Engram is unreachable, the app exits with a clear error. + +In another terminal: + +```bash +# Tell the agent a fact — it stores it in Engram +curl -s -X POST "localhost:8080/chat?session=alice" \ + -H "Content-Type: text/plain" \ + -d "I work at Acme as a Java engineer" +# → {"session":"alice","reply":"Got it, I've stored that you work at Acme as a Java engineer."} + +# Ask about it — agent recalls from Engram +curl -s -X POST "localhost:8080/chat?session=alice" \ + -H "Content-Type: text/plain" \ + -d "Where do I work?" +# → {"session":"alice","reply":"You work at Acme."} + +# The first message also contained "Java engineer" — Engram extracted that too +curl -s -X POST "localhost:8080/chat?session=alice" \ + -H "Content-Type: text/plain" \ + -d "What languages do I use?" +# → {"session":"alice","reply":"Based on what you've shared, you're a Java engineer."} +``` + +Each response is a JSON object `{"session": "...", "reply": "..."}`. + +## See the trace in JamJet Cloud + +Open [cloud.jamjet.dev/dashboard/graph](https://cloud.jamjet.dev/dashboard/graph) — each `/chat` call appears as a trace with: + +- 1 LLM span (OpenAI chat completion) +- 1 or more Engram tool spans (`rememberFact` or `recallFacts`) +- Cost rollup (per-token, per-call) + +## Anatomy + +The interesting code is ~120 LOC across 4 files: + +| File | What it does | +|---|---| +| `MemoryTools.java` | `@Tool` methods (`rememberFact`, `recallFacts`) backed by autoconfigured `EngramClient` | +| `MemoryAgent.java` | Spring AI `ChatClient` wired with the tools + system prompt | +| `ChatController.java` | `POST /chat?session=X` — accepts `text/plain`, returns `{"session","reply"}` | +| `startup/PreflightCheck.java` | Validates env vars + polls Engram `/health` before the app accepts traffic | + +The pom has three starter dependencies. Zero custom plumbing. + +## Configuration + +| Property | Default | Purpose | +|---|---|---| +| `engram.base-url` | `http://127.0.0.1:9090` | Where the autoconfigured `EngramClient` connects | +| `spring.ai.openai.api-key` | `${OPENAI_API_KEY}` | Spring AI OpenAI key | +| `spring.ai.openai.chat.options.model` | `gpt-4o-mini` | OpenAI model for chat | +| `jamjet.cloud.api-key` | `${JAMJET_API_KEY}` | JamJet Cloud project key | +| `jamjet.cloud.api-url` | `https://api.jamjet.dev` | JamJet Cloud ingest endpoint | + +To swap the chat model (e.g. to `gpt-4o`), edit `application.yml`. To use a different LLM provider for Engram's fact extraction, change `ENGRAM_LLM_PROVIDER` in `docker-compose.yml` — see [Engram's provider docs](https://github.com/jamjet-labs/jamjet/tree/main/runtime/engram-server#llm-providers). + +## Windows notes + +- Use PowerShell or cmd; `mvnw.cmd` is the entry point instead of `./mvnw`. +- WSL2 users: run from the WSL side for cleanest networking with Docker Desktop. +- The `ghcr.io/jamjet-labs/engram-server:0.5.0` image is multi-arch; Docker Desktop on Windows ARM should work with Linux containers enabled. + +## Cleaning up + +```bash +docker compose down # stops Engram, removes container + volume +# Press Ctrl-C on the Spring app +``` + +When you're done, rotate or delete your JamJet API key and OpenAI key in their respective dashboards — they are tied to your account quotas. + +## Security + +- `.env` is in `.gitignore` — never commit your keys. +- Both Engram and the Spring app bind to `127.0.0.1`. Do not expose this demo on a public network. +- For real apps with PII in prompts, enable [JamJet's redaction settings](https://docs.jamjet.dev/redaction) (Team tier and up). The demo runs on the free tier without redaction — do not pipe production traffic through it. + +## What's next + +- **The new Python Engram rewrite** (`jamjet-engram` 0.1.0) is the next-generation server — more featureful, better benchmarks, but currently has wire-protocol gaps with the Java starter. Once those gaps close, the docker-compose image is a one-line swap. +- **A separate MCP demo** (`examples/mcp-engram-demo/`, coming soon) targets MCP-protocol-native clients (Cursor, Claude Desktop) instead of Spring Boot ergonomics. +- Read the [JamJet Spring AI integration guide](../../docs/spring-ai-integration.md). + +## License + +Apache 2.0. See [LICENSE](../../LICENSE). From 6815fc11064c26bcfbd360008d449156338a63ec Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 22:06:29 +0530 Subject: [PATCH 14/16] =?UTF-8?q?fix(demo):=20boot=20wiring=20=E2=80=94=20?= =?UTF-8?q?pull=20in=20langchain4j-core=20for=20cloud=20starter;=20@Autowi?= =?UTF-8?q?red=20on=20PreflightCheck=20production=20constructor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/spring-ai-engram-cloud-demo/pom.xml | 9 +++++++++ .../demo/springaiengram/startup/PreflightCheck.java | 2 ++ 2 files changed, 11 insertions(+) diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml index cf67d7d..7e250b7 100644 --- a/examples/spring-ai-engram-cloud-demo/pom.xml +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -69,6 +69,15 @@ jamjet-cloud-spring-boot-starter ${jamjet-cloud.version} + + + dev.langchain4j + langchain4j-core + 0.36.2 + org.springframework.boot diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java index c97c1ba..2216b1c 100644 --- a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/startup/PreflightCheck.java @@ -1,5 +1,6 @@ package dev.jamjet.demo.springaiengram.startup; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -20,6 +21,7 @@ public class PreflightCheck implements ApplicationRunner { private final Map env; private final String engramHealthUrl; + @Autowired public PreflightCheck(@Value("${app.engram.health-url:http://127.0.0.1:9090/health}") String engramHealthUrl) { this(System.getenv(), engramHealthUrl); } From 56411817c8c1ec3e46ed5a59e6e52ff3c5a88a73 Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 22:10:50 +0530 Subject: [PATCH 15/16] fix(demo): add spring-boot-starter-actuator so JamjetObservationHandler auto-registers --- examples/spring-ai-engram-cloud-demo/pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml index 7e250b7..f48d979 100644 --- a/examples/spring-ai-engram-cloud-demo/pom.xml +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -55,6 +55,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + org.springframework.ai spring-ai-starter-model-openai From 242e328ed3e2aaa59e0e3649b89dbfa2ea51992c Mon Sep 17 00:00:00 2001 From: sdev Date: Thu, 7 May 2026 22:56:02 +0530 Subject: [PATCH 16/16] =?UTF-8?q?fix(demo):=20cloud=20observability=20?= =?UTF-8?q?=E2=80=94=20drop=20buggy=20starter,=20wire=20JamjetObservationH?= =?UTF-8?q?andler=20directly=20with=20context-type=20filter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop dev.jamjet:jamjet-cloud-spring-boot-starter:0.2.0 dep. Its autoconfig hard-references LangChain4j classes which forced langchain4j-core onto the classpath of a Spring-AI-only app. - Depend on dev.jamjet:jamjet-cloud-sdk:0.2.0 directly + add JamjetCloudConfiguration in the demo that does the Spring AI half. Cleaner separation; pattern can be upstreamed as a 'Spring AI only' autoconfig. - Workaround for jamjet-cloud-sdk:0.2.0 JamjetObservationHandler.supportsContext bug: it filters by name.startsWith('gen_ai.client'), but Micrometer calls supportsContext at points where ctx.getName() is still null — handler is never selected. Replace name-based filter with context-class filter so selection is name-independent. - Verified end-to-end: chat-driven gen_ai.client.operation observations now flow to JamJet Cloud (traces with llm_call counts + cost rollups visible at /v1/traces). Tested with 3 README curls; 6 demo traces persisted at JamJet. --- examples/spring-ai-engram-cloud-demo/pom.xml | 16 ++-- .../cloud/JamjetCloudConfiguration.java | 73 +++++++++++++++++++ .../springaiengram/DemoIntegrationTest.java | 5 -- 3 files changed, 81 insertions(+), 13 deletions(-) create mode 100644 examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/cloud/JamjetCloudConfiguration.java diff --git a/examples/spring-ai-engram-cloud-demo/pom.xml b/examples/spring-ai-engram-cloud-demo/pom.xml index f48d979..7047a62 100644 --- a/examples/spring-ai-engram-cloud-demo/pom.xml +++ b/examples/spring-ai-engram-cloud-demo/pom.xml @@ -70,19 +70,19 @@ engram-spring-boot-starter ${jamjet-engram.version} + dev.jamjet - jamjet-cloud-spring-boot-starter + jamjet-cloud-sdk ${jamjet-cloud.version} - + - dev.langchain4j - langchain4j-core - 0.36.2 + io.micrometer + micrometer-observation diff --git a/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/cloud/JamjetCloudConfiguration.java b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/cloud/JamjetCloudConfiguration.java new file mode 100644 index 0000000..0200b65 --- /dev/null +++ b/examples/spring-ai-engram-cloud-demo/src/main/java/dev/jamjet/demo/springaiengram/cloud/JamjetCloudConfiguration.java @@ -0,0 +1,73 @@ +package dev.jamjet.demo.springaiengram.cloud; + +import dev.jamjet.cloud.JamjetCloud; +import dev.jamjet.cloud.JamjetCloudConfig; +import dev.jamjet.cloud.instrumentation.spring.JamjetObservationHandler; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; +import io.micrometer.observation.ObservationRegistry; +import jakarta.annotation.PostConstruct; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +/** + * Wires JamJet Cloud observability into the demo. + * + *

We deliberately do NOT use jamjet-cloud-spring-boot-starter:0.2.0 because its + * autoconfig hard-references LangChain4j classes — would force langchain4j-core onto + * the classpath of a Spring-AI-only app. Instead we configure the SDK directly and + * register the Spring AI observation handler explicitly with the ObservationRegistry. + * + *

This pattern can be upstreamed as a "Spring AI only" autoconfig in a future + * cloud starter release. + */ +@Configuration +public class JamjetCloudConfiguration { + + private static final Logger LOG = LoggerFactory.getLogger(JamjetCloudConfiguration.class); + + private final String apiKey; + private final String apiUrl; + private final ObservationRegistry observationRegistry; + + public JamjetCloudConfiguration( + @Value("${jamjet.cloud.api-key}") String apiKey, + @Value("${jamjet.cloud.api-url:https://api.jamjet.dev}") String apiUrl, + ObservationRegistry observationRegistry) { + this.apiKey = apiKey; + this.apiUrl = apiUrl; + this.observationRegistry = observationRegistry; + } + + @PostConstruct + void initJamjetCloud() { + JamjetCloud.configure(JamjetCloudConfig.builder() + .apiKey(apiKey) + .apiUrl(apiUrl) + .agentName("spring-ai-engram-demo") + .build()); + + // Workaround for jamjet-cloud-spring-boot-starter:0.2.0: + // 1. Its autoconfig hard-references LangChain4j classes — would force langchain4j-core + // onto the classpath of a Spring-AI-only app. We bypass it and wire ourselves. + // 2. Its JamjetObservationHandler.supportsContext filters by `name.startsWith("gen_ai.client")`, + // but Micrometer calls supportsContext while the context name is still null — + // the handler would never be selected. We use a context-class filter instead so the + // decision is name-independent. + // Both are filed as upstream followups; remove this @Configuration once they ship. + JamjetObservationHandler jamjet = new JamjetObservationHandler(); + observationRegistry.observationConfig().observationHandler(new ObservationHandler<>() { + @Override + public boolean supportsContext(Observation.Context ctx) { + return ctx != null + && ctx.getClass().getName().equals("org.springframework.ai.chat.observation.ChatModelObservationContext"); + } + @Override public void onStart(Observation.Context ctx) { jamjet.onStart(ctx); } + @Override public void onStop(Observation.Context ctx) { jamjet.onStop(ctx); } + }); + + LOG.info("JamJet Cloud configured -> {} (agent=spring-ai-engram-demo)", apiUrl); + } +} diff --git a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java index 19712a0..1314aec 100644 --- a/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java +++ b/examples/spring-ai-engram-cloud-demo/src/test/java/dev/jamjet/demo/springaiengram/DemoIntegrationTest.java @@ -2,12 +2,10 @@ import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; -import dev.jamjet.cloud.spring.JamjetCloudAutoConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.web.client.RestTemplateBuilder; @@ -25,9 +23,6 @@ @ActiveProfiles("test") @Testcontainers -// JamjetCloudAutoConfiguration 0.2.0 references langchain4j which is not on the test classpath; -// exclude it to avoid ClassNotFoundException during condition processing. -@EnableAutoConfiguration(exclude = JamjetCloudAutoConfiguration.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class DemoIntegrationTest {