diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6f6132878..0ed2233f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -56,7 +56,7 @@ jobs:
- name: SpotBugs Check
# Generated examples are verified by the dedicated Example Gate. They
# intentionally do not inherit the runtime's SpotBugs build plugin.
- run: mvn spotbugs:check -pl '!examples/conformance/lib,!examples/conformance'
+ run: mvn spotbugs:check -pl '!examples/conformance/java-lib-core/lib,!examples/conformance/java-app-console'
- name: Verify trusted snapshot selection policy
run: node --test .github/scripts/select-odc-snapshot.test.cjs
- name: Verify snapshot freshness policy
@@ -88,10 +88,10 @@ jobs:
-Dformats=HTML,JSON
- name: OWASP Dependency Check standalone generated examples
run: |
- mvn -B -f examples/school-management/lib/pom.xml install -DskipTests
+ mvn -B -f examples/school-management/java-lib-core/lib/pom.xml install -DskipTests
for pom in \
- examples/school-management/lib/pom.xml \
- examples/school-management/pom.xml \
+ examples/school-management/java-lib-core/lib/pom.xml \
+ examples/school-management/java-app-console/pom.xml \
examples/order-management/java-lib-core/lib/pom.xml; do
mvn -B -f "$pom" org.owasp:dependency-check-maven:13.0.0:check \
-DdataDirectory=${{ runner.temp }}/teaql-odc-data \
diff --git a/.github/workflows/example-gate.yml b/.github/workflows/example-gate.yml
index 92c19eea1..1a060507b 100644
--- a/.github/workflows/example-gate.yml
+++ b/.github/workflows/example-gate.yml
@@ -73,6 +73,11 @@ jobs:
# Keep its offline checks; prepare a fresh runner before they start.
run: |
mvn -B -ntp install
+ # These standalone console dependencies are absent from generated
+ # library manifests and are used by the offline workspace checks.
+ for artifact in com.zaxxer:HikariCP:6.3.0 org.mybatis:mybatis:3.5.19 org.codehaus.mojo:exec-maven-plugin:3.5.0; do
+ mvn -B -ntp org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get "-Dartifact=$artifact"
+ done
node <<'NODE'
const fs = require('node:fs'), path = require('node:path'), os = require('node:os'), cp = require('node:child_process');
const runtime = process.cwd(), owned = fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-ci-example-dependencies-'));
@@ -88,6 +93,20 @@ jobs:
cp.execFileSync('mvn', ['-B', '-ntp', '-f', selected,
'org.apache.maven.plugins:maven-dependency-plugin:3.8.1:go-offline'], {stdio: 'inherit'});
}
+ // Resolve the standalone console reactor's actual mediated runtime
+ // dependencies. Dependency go-offline alone visits a different
+ // Netty version through this workspace's Spring/AWS dependency graph.
+ const attachmentSource = path.join(runtime, 'examples/object-storage');
+ const attachment = path.join(owned, 'order-attachment-workspace');
+ fs.mkdirSync(attachment);
+ fs.copyFileSync(path.join(attachmentSource, 'workspace-pom.xml'), path.join(attachment, 'pom.xml'));
+ for (const role of ['java-lib-core', 'java-app-console']) {
+ fs.cpSync(path.join(attachmentSource, role), path.join(attachment, role), {
+ recursive: true, filter: file => path.basename(file) !== 'target',
+ });
+ }
+ cp.execFileSync('mvn', ['-B', '-ntp', '-f', path.join(attachment, 'pom.xml'),
+ '-DskipTests', 'install'], {stdio: 'inherit'});
} finally {
fs.rmSync(owned, {recursive: true});
}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 66d146fd9..1ed681254 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -53,7 +53,7 @@ jobs:
fi
- name: Publish all Maven modules
if: github.event_name == 'push'
- run: mvn -B deploy -DskipTests -pl '!examples/conformance/lib,!examples/conformance'
+ run: mvn -B deploy -DskipTests -pl '!examples/conformance/java-lib-core/lib,!examples/conformance/java-app-console'
env:
TEAQL_MAVEN_USERNAME: ${{ secrets.TEAQL_MAVEN_USERNAME }}
TEAQL_MAVEN_PASSWORD: ${{ secrets.TEAQL_MAVEN_PASSWORD }}
diff --git a/README.md b/README.md
index 4024633b9..11bed4817 100644
--- a/README.md
+++ b/README.md
@@ -74,7 +74,7 @@ own Java APIs.
These application-code excerpts assume the example's generated imports, trusted
Context and an existing object identity. `Q` and `E` belong to the generated
domain library, not a generic runtime object with arbitrary field strings.
-See the [application source](examples/school-management/src/main/java/com/example/schoolmanagementservice/SchoolLifecycleVerifier.java) for complete setup.
+See the [application source](examples/school-management/java-app-console/src/main/java/com/example/schoolmanagementservice/SchoolLifecycleVerifier.java) for complete setup.
```java
var schoolTypeDetails = Q.schoolTypesWithMinimalFields().selectCode();
diff --git a/examples/business-id-runtime/README.md b/examples/business-id-runtime/README.md
index 3b959c99a..a4ab27cee 100644
--- a/examples/business-id-runtime/README.md
+++ b/examples/business-id-runtime/README.md
@@ -1,4 +1,12 @@
-# Business ID focused runtime example
+# Number two procurement orders
+
+`model.xml` defines the purchase order and its `ORD` Business ID.
+`java-lib-core/` contains the generated domain library. The console at
+`java-app-console/src/main/java/com/teaql/purchaseordernumbering/App.java` installs the trusted business clock and SQLite allocator,
+records two orders, retries the first, and reads both back by number.
+It rejects a blank audit reason and verifies the denied order is absent.
+
+## Allocator and live-dialect calibration
This example verifies the Java runtime Business ID boundary without running
the full multi-module regression suite. It covers the default six-character
diff --git a/examples/business-id-runtime/java-app-console/.gitignore b/examples/business-id-runtime/java-app-console/.gitignore
new file mode 100644
index 000000000..fe5546972
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/.gitignore
@@ -0,0 +1,53 @@
+
+*.gz
+target/
+
+### IntelliJ IDEA ###
+.idea/*
+.idea/modules.xml
+.idea/jarRepositories.xml
+.idea/compiler.xml
+.idea/libraries/
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### NetBeans ###
+/nbproject/private/
+/dist/
+/nbdist/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store
+
+*.class
+*.log
+*.contextt
+.mtj.tmp/
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+hs_err_pid*
+replay_pid*
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/AGENTS.md b/examples/business-id-runtime/java-app-console/AGENTS.md
new file mode 100644
index 000000000..60b120b36
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/AGENTS.md
@@ -0,0 +1,66 @@
+
+
+# TeaQL Java Agent Instructions
+
+## TeaQL workspace rules
+
+- Work in application-owned files. Keep the generated domain library read-only.
+- Discover API names and signatures through model-aware Assist only.
+ Do not read or search generated library source for API discovery. Use the
+ original evaluated KSML file or directory and its exact entity and field names.
+- Ask for the current entity and action first. Request field-level query help
+ only for the fields you use. If Assist lacks the operation, report
+ `MISSING_ASSIST` with the entity, action, and relevant field or diagnostic.
+
+```text
+cargo teaql --input [model] java-assist-[action]/[entity]
+cargo teaql --input [model] java-assist-query/[entity].[field]
+```
+
+Replace the bracketed values with the actual model path, action, entity, and
+field. Actions include `query`, `list-page`, `create`, `update`, `delete`, and
+`expression`. Validate API usage by compiling and testing the application.
+
+- Use the trusted `UserContext` as the only runtime argument for generated query
+ execution and saves. Resolve tenant, actor, authorization, and provider
+ resources from trusted application setup.
+- Keep queries bounded and provide a non-empty purpose and comment. Supply a
+ non-empty audit reason for writes through the API shown by Assist.
+
+> [!WARNING]
+> **IGNORE GENERIC ORM EXPERIENCE**
+>
+> Do **not** use pre-trained habits from data-access frameworks, ORMs, or database integration libraries.
+>
+> Do **not** use MyBatis, JPA, Hibernate, Spring Data, MyBatis-Plus, or similar frameworks.
+>
+> Do **not** write raw SQL, DAOs, Repository implementations, or custom persistence layers.
+>
+> Do **not** guess TeaQL method names.
+
+## Model entities
+
+| entity-name | display-name |
+|-------------|--------------|
+| platform | platform |
+| purchase_order | purchase_order |
+
+
+## Application entry and context
+
+Start in `App.java` under `src/main/java`. The console assembles the
+`TeaQLRuntime` and creates its `UserContext` with `new CustomUserContext(runtime)`.
+
+## Additional References
+
+Read these only when the task requires them:
+
+* **`TOOL_API_GUIDE.md`**
+ Framework runtime references and context handling.
+
+* **`RUNTIME_CUSTOM_GUIDE.md`**
+ Runtime setup, debugging, and project-specific restrictions.
+
+## Optional standard telemetry
+
+See [STANDARD_TELEMETRY.md](STANDARD_TELEMETRY.md) for the selected runtime's optional module, trusted activation variables and safe startup diagnostics.
diff --git a/examples/business-id-runtime/java-app-console/DOMAIN_API_GUIDE.md b/examples/business-id-runtime/java-app-console/DOMAIN_API_GUIDE.md
new file mode 100644
index 000000000..b1c6d4a93
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/DOMAIN_API_GUIDE.md
@@ -0,0 +1,29 @@
+
+**ATTENTION AI AGENTS:** Do not guess TeaQL API methods! To get the exact API usage and query examples for the entity you are working on, you must fetch the dynamically generated prompt directly from the code generation server. Use your tools to execute the following command to download the exact contextual prompt for the entity:
+
+```bash
+cargo teaql --input models/purchase-order-numbering.xml java-assist-[action]/[entity-name]
+```
+
+Replace `[entity-name]` with the exact entity-name of the entity.
+
+**Available candidate entities in this model:**
+
+| entity-name | display-name |
+|-------------|--------------|
+| platform | platform |
+| purchase_order | purchase_order |
+
+
+Replace `[action]` with one of the following depending on what you are trying to write:
+
+| action | when-to-use |
+|--------|-------------|
+| query | You need to read/find records from the database using Q:: |
+| create | You need to insert a new record into the database |
+| update | You need to modify and save an existing record |
+| delete | You need to remove or soft-delete a record |
+| expression | You need to safely extract nested relation values (avoiding null panics) using the E:: facade |
+| list-page | You need to implement a paginated query returning a SmartList |
+
+Once the command succeeds, read its output. Use the printed code as a template to write your logic.
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/Makefile b/examples/business-id-runtime/java-app-console/Makefile
new file mode 100644
index 000000000..80a7574a4
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/Makefile
@@ -0,0 +1,32 @@
+
+# TEAQL WARNING: This project uses TeaQL. TeaQL was explicitly designed to PREVENT AI hallucinations and random guessing.
+# AI AGENTS MUST STRICTLY USE THESE MAKE TARGETS ONLY. Do NOT guess other build commands.
+
+.PHONY: build test run clean help generate-lib
+
+# Default target
+help:
+ @echo "Available commands:"
+ @echo " make generate-lib - Regenerate the TeaQL domain library"
+ @echo " make build - Build the Java console application (mvn clean package)"
+ @echo " make test - Run application tests (mvn test)"
+ @echo " make run - Run the application locally (java -jar target/purchase-order-numbering-0.0.1-SNAPSHOT.jar)"
+ @echo " make clean - Clean the project"
+
+generate-lib:
+ @echo "Regenerating TeaQL library..."
+ ./gen-lib.sh || echo "Please ensure gen-lib.sh exists or run teaql code generator manually"
+
+build:
+ mvn -f ../java-lib-core/lib/pom.xml install -DskipTests
+ mvn clean package -DskipTests
+
+test:
+ mvn -f ../java-lib-core/lib/pom.xml install -DskipTests
+ mvn test
+
+run: build
+ java -jar target/purchase-order-numbering-0.0.1-SNAPSHOT.jar
+
+clean:
+ mvn clean
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/RUNTIME_CUSTOM_GUIDE.md b/examples/business-id-runtime/java-app-console/RUNTIME_CUSTOM_GUIDE.md
new file mode 100644
index 000000000..664ead2a8
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/RUNTIME_CUSTOM_GUIDE.md
@@ -0,0 +1,25 @@
+
+# TeaQL Runtime Customization Guide
+
+This is a plain Java console application. `App.main()` creates and closes the Hikari
+DataSource, wraps it with `JdbcSqlExecutor`, and manually assembles `TeaQLRuntime.builder()`.
+The generated runtime module installs metadata and runtime services; `CustomUserContext`
+is then created explicitly and `context.ensureSchema()` initializes the database.
+
+Run `make run` to install the generated library, package the application, and launch it.
+Configuration is loaded from `src/main/resources/application.properties`. Override values
+with JVM properties or `--teaql.datasource.url=jdbc:...` command-line arguments.
+Server database credentials use `TEAQL_DATABASE_USERNAME` and `TEAQL_DATABASE_PASSWORD`.
+Keep business operations in the generated Q/E APIs and audited entity saves.
+
+> [!WARNING]
+> **DO NOT GUESS RUNTIME CONFIGURATION**
+> Do not guess how to configure the runtime, connection pools, or schema generation.
+
+To get the exact usage and examples for Customizing the Runtime (UserContext assembly, SQL debugging, Schema modes), you must fetch the dynamically generated prompt directly from the code generation server. Use your tools to execute the following command:
+
+```bash
+cargo teaql --input models/purchase-order-numbering.xml java-assist-runtime-custom
+```
+
+Once the command succeeds, read its output. Use the printed code as a template to write your logic.
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/STANDARD_TELEMETRY.md b/examples/business-id-runtime/java-app-console/STANDARD_TELEMETRY.md
new file mode 100644
index 000000000..e8ec83d43
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/STANDARD_TELEMETRY.md
@@ -0,0 +1,45 @@
+## Standard OpenTelemetry module
+
+Use the optional standard module supplied by the selected TeaQL runtime. Match
+its version to the runtime dependency selected by the model and workspace;
+keep local source or internal Registry overrides during development. Do not
+upgrade to an unrelated public release just to enable telemetry. A runtime
+without this module reports `module_unavailable`; package installation alone
+does not enable export.
+
+On a supported backend, configure these trusted process variables before startup, never
+through a query, JSON or TFP payload:
+
+```bash
+export TEAQL_TELEMETRY_ENABLED=true
+export TEAQL_TELEMETRY_SERVICE_NAME=payment-service
+export TEAQL_TELEMETRY_OTLP_ENDPOINT=http://localhost:4318
+```
+
+Without enablement, startup reports `disabled` and all three activation variables;
+no SDK export resources are created. Enabled startup reports safe effective
+settings, full recording and masking. Invalid settings produce a fixed safe
+diagnostic, not a claim of successful export. Never print credentials or raw
+configuration values.
+
+The module automatically records supported Q, graph mutation and physical SQL
+operations as traces, logs and metrics. SQL is expanded with masked parameters;
+plaintext debugging never authorizes plaintext telemetry export. Full recording
+does not promise lossless delivery when bounded queues or exporters fail.
+Do not add per-method spans or replace the customer's global SDK providers.
+
+Keep schema reconciliation explicit. Run the generated ensure-schema and seed
+flow through the same configured runtime to observe startup settings and audited,
+idempotent seeding. Telemetry setup must not run ensure-schema implicitly.
+Flush and shut down the owned pipeline at application shutdown, not per query.
+Exporter failures do not change business results; durable business audit remains
+an independent path.
+
+
+### Java assembly
+
+Add the optional Maven artifact `io.teaql:teaql-opentelemetry` to the application,
+using the exact same version as its TeaQL runtime dependency. Keep it out of the
+generated domain library's mandatory dependencies. TeaQLRuntime discovers the
+module through ServiceLoader at startup; no application SDK initialization is
+required. Set the three variables before starting the JVM.
diff --git a/examples/business-id-runtime/java-app-console/TOOL_API_GUIDE.md b/examples/business-id-runtime/java-app-console/TOOL_API_GUIDE.md
new file mode 100644
index 000000000..87ef3ecd1
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/TOOL_API_GUIDE.md
@@ -0,0 +1,31 @@
+
+# TeaQL Tool & Runtime API Reference
+
+> [!WARNING]
+> **DO NOT GUESS FRAMEWORK APIS**
+> Do not guess how to use `UserContext`, `SmartList`, `WebResponse`, or how to manage transactions.
+
+> [!IMPORTANT]
+> **USE TEAQL'S OWN TOOLING FIRST**
+> Always use `cargo teaql` to retrieve assist content. Never bypass the CLI or invoke the generator endpoint directly.
+
+To get the exact API usage and examples for Framework-level APIs (UserContext, SmartList, WebResponse, Entity Expression, Checkers, etc.), you must fetch the dynamically generated prompt directly from the code generation server. Use your tools to execute the following command:
+
+```bash
+cargo teaql --input models/purchase-order-numbering.xml java-assist-tool-api
+```
+
+Once the command succeeds, read its output. Use the printed code as a template to write your logic.
+
+## Domain Object Assist APIs
+
+If you need reference code or tool APIs specifically tailored for your domain objects (e.g., `user`, `order`), TeaQL provides code generators that yield perfect, ready-to-copy Java code snippets.
+
+You can query these assist APIs for any object defined in your `models/purchase-order-numbering.xml`:
+
+| Target | Description | Example Command |
+|--------|-------------|-----------------|
+| `java-assist-query/[object]` | How to query and filter `[object]` | `cargo teaql --input models/purchase-order-numbering.xml java-assist-query/school` |
+| `java-assist-create/[object]` | How to insert/create `[object]` | `cargo teaql --input models/purchase-order-numbering.xml java-assist-create/school` |
+| `java-assist-update/[object]` | How to update `[object]` | `cargo teaql --input models/purchase-order-numbering.xml java-assist-update/school` |
+| `java-assist-delete/[object]` | How to delete `[object]` | `cargo teaql --input models/purchase-order-numbering.xml java-assist-delete/school` |
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/docs/teaql-java-crud-guide.md b/examples/business-id-runtime/java-app-console/docs/teaql-java-crud-guide.md
new file mode 100644
index 000000000..fdab6a8e6
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/docs/teaql-java-crud-guide.md
@@ -0,0 +1,136 @@
+
+# TeaQL Java CRUD Guide
+
+Generated for `com.teaql.purchaseordernumbering`. Use this guide when adding controllers, services, jobs, or integration code in this workspace.
+
+## Setup
+
+```java
+import com.teaql.purchaseordernumbering.Q;
+import com.teaql.purchaseordernumbering.PurchaseOrderNumberingUserContext;
+import io.teaql.core.web.WebResponse;
+```
+
+The console entry point manually builds TeaQLRuntime and creates `new CustomUserContext(runtime)`.
+Pass that context to generated Q/E APIs and audited saves.
+
+## Non-Negotiable Database Rule
+
+Never use SQL to operate on the database from workspace business code. This includes select, insert, update, delete, schema changes, JDBC templates, native queries, direct repositories, and ad hoc SQL helpers.
+
+If the generated TeaQL API does not provide a path for the requested change, stop and report the missing API. Do not implement a SQL workaround.
+
+## Mandatory Update Method Rule
+
+Use generated `updateXxx(...)` methods for all entity field changes. Do not use `setXxx(...)` in new code. Setters are deprecated even when the IDE or generated class makes them visible.
+
+```java
+entity.updateName("new value");
+```
+
+Do not write:
+
+```java
+entity.setName("new value");
+```
+
+## Read One Entity
+
+Prefer typed generated query entry points. Controller methods that return one object should wrap the result in `WebResponse.of(...)`:
+
+```java
+public WebResponse getOne(@TQLContext UserContext userContext, Long id) {
+ try {
+ var entity = Q.platforms()
+ .filterById(id)
+ .selectSelf()
+ .comment("load detail by id")
+ .purpose("get task detail")
+ .executeForOne(userContext);
+ return WebResponse.of(entity);
+ } catch (Exception e) {
+ return WebResponse.fail(e.getMessage());
+ }
+}
+```
+
+## Read A Page
+
+Controller methods that return multiple objects should wrap the list in `WebResponse.of(...)`:
+
+```java
+public WebResponse list(@TQLContext UserContext userContext) {
+ try {
+ var list = Q.platforms()
+ .selectSelf()
+ .page(1, 20)
+ .comment("list tasks")
+ .purpose("render dashboard list")
+ .executeForList(userContext);
+ return WebResponse.of(list);
+ } catch (Exception e) {
+ return WebResponse.fail(e.getMessage());
+ }
+}
+```
+
+## Create
+
+```java
+var entity = new Platform();
+// Fill fields with generated updateXxx(...) methods, not setXxx(...).
+entity.auditAs("Create new item").save(userContext);
+```
+
+## Update
+
+```java
+var entity = Q.platforms()
+ .filterById(id)
+ .selectSelf()
+ .comment("load for update")
+ .purpose("edit entity")
+ .executeForOne(userContext);
+
+// Use updateXxx(...) methods for state changes.
+// entity.updateName("new value");
+entity.auditAs("Update entity properties").save(userContext);
+```
+
+## Load Relations
+
+Use generated selectors. Do not write a loop that queries children one row at a time. The examples below focus on the entities with the highest reverse relation counts because they are stronger aggregate-root candidates.
+
+```java
+var list = Q.platforms()
+ .selectPurchaseOrderListWith(Q.purchaseOrders().selectSelf())
+ .comment("load with purchaseOrderList")
+ .purpose("fetch child purchaseOrderList")
+ .executeForList(userContext);
+```
+
+
+## Delete
+
+Use `java-assist-delete/[entity]` with the original KSML input to get the exact
+soft-delete API. If Assist lacks the operation, report `MISSING_ASSIST`.
+
+Do not hard-delete rows. Do not write SQL `DELETE` or `UPDATE` statements. If the soft-delete API is not visible, stop and report that blocker instead of changing data through SQL.
+
+## Common Mistakes
+
+- Do not instantiate repositories directly in workspace business code.
+- Do not use SQL for any database operation.
+- Do not use deprecated `setXxx(...)` methods for updates. Use `updateXxx(...)`.
+- Do not return raw entities or lists from controller query methods. Return `WebResponse.of(entity)` or `WebResponse.of(list)`.
+- Do not forget `.executeForOne(userContext)` or `.executeForList(userContext)`.
+- Do not forget `.comment("...")` and `.purpose("...")` on queries.
+- Do not forget `.auditAs("...")` before calling `.save(context)` on entities.
+- Do not assume relations are loaded unless the query selected them.
+- Do not bypass `UserContext`; context carries logging, tenant, security, and repository resolution behavior.
+
+## Entity Cheat Sheet
+
+These entities are selected by reverse relation count, not by model declaration order.
+
+- `Platform`: reverse relations `1`, query `Q.platforms()`, save `new Platform().auditAs("comment").save(userContext)`, request `com.teaql.purchaseordernumbering.platform.PlatformRequest`
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/pom.xml b/examples/business-id-runtime/java-app-console/pom.xml
new file mode 100644
index 000000000..a85853740
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/pom.xml
@@ -0,0 +1,103 @@
+
+
+
+ 4.0.0
+
+ com.teaql
+ purchase-order-numbering
+ 0.0.1-SNAPSHOT
+ jar
+
+
+ 21
+ 0.0.1-SNAPSHOT
+ UTF-8
+ true
+ 6.3.0
+
+
+
+
+ aliyun-public
+ https://maven.aliyun.com/nexus/content/groups/public/
+
+
+ teaql
+ https://maven.teaql.io/repository/maven-releases/
+
+
+
+
+
+ io.teaql
+ teaql-provider-jdbc
+ ${teaql.version}
+
+
+ io.teaql
+ teaql-data-service-sql
+ ${teaql.version}
+
+
+ io.teaql
+ teaql-business-id-jdbc
+ ${teaql.version}
+
+
+ com.zaxxer
+ HikariCP
+ 6.3.0
+
+
+ org.xerial
+ sqlite-jdbc
+ 3.53.2.1
+
+ com.teaql
+ purchase-order-numbering-core
+ ${libversion}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.12.1
+
+ ${java.version}
+ ${maven.compiler.parameters}
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 3.6.0
+
+ package
+ shade
+
+ false
+
+ *:*
+
+ META-INF/*.SF
+ META-INF/*.RSA
+ META-INF/*.DSA
+
+
+
+
+
+ com.teaql.purchaseordernumbering.App
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/App.java b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/App.java
new file mode 100644
index 000000000..4e03dea0a
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/App.java
@@ -0,0 +1,120 @@
+
+package com.teaql.purchaseordernumbering;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import java.util.Properties;
+
+import io.teaql.core.meta.EntityMetaFactory;
+import io.teaql.core.meta.SimpleEntityMetaFactory;
+import io.teaql.core.DataServiceExecutor;
+import io.teaql.core.DataServiceRegistry;
+import io.teaql.core.sql.portable.IdSpaceIdGenerator;
+import io.teaql.businessid.jdbc.JdbcBusinessIdAllocator;
+import io.teaql.core.businessid.BusinessIdEncodingKey;
+import io.teaql.runtime.businessid.StaticBusinessIdKeyProvider;
+import java.util.HexFormat;
+import io.teaql.core.UserContext;
+import io.teaql.provider.jdbc.JdbcSqlExecutor;
+import io.teaql.runtime.TeaQLRuntime;
+import javax.sql.DataSource;
+
+public class App {
+
+ public static void main(String[] args) throws Exception {
+ Properties properties = new Properties();
+ try (var input = App.class.getResourceAsStream("/application.properties")) {
+ if (input != null) properties.load(input);
+ }
+ for (String arg : args) {
+ if (!arg.startsWith("--") || !arg.contains("=")) {
+ throw new IllegalArgumentException("Expected --key=value argument");
+ }
+ int separator = arg.indexOf('=');
+ properties.setProperty(arg.substring(2, separator), arg.substring(separator + 1));
+ }
+ HikariConfig config = new HikariConfig();
+ config.setJdbcUrl(setting(properties, "teaql.datasource.url"));
+ String driver = setting(properties, "teaql.datasource.driver-class-name");
+ if (driver != null) config.setDriverClassName(driver);
+ String username = setting(properties, "teaql.datasource.username");
+ String password = setting(properties, "teaql.datasource.password");
+ if (username != null) config.setUsername(username);
+ if (password != null) config.setPassword(password);
+ try (HikariDataSource source = new HikariDataSource(config)) {
+ App app = new App();
+ JdbcSqlExecutor executor = new JdbcSqlExecutor(source);
+ TeaQLRuntime runtime = app.teaQLRuntime(app.entityMetaFactory(),
+ app.dataServiceRegistry(app.dataServiceExecutor(executor, source)),
+ app.teaQLDatabase(executor, source));
+ UserContext context = new CustomUserContext(runtime);
+ context.ensureSchema();
+ PurchaseOrderNumbering.verify(context, System.getenv("TEAQL_PURCHASE_NUMBERING_ROUND"));
+ }
+ }
+
+ private static String setting(Properties properties, String key) {
+ String value = System.getProperty(key, properties.getProperty(key));
+ if (value != null && value.startsWith("${") && value.endsWith("}")) {
+ String variable = value.substring(2, value.length() - 1);
+ value = System.getenv(variable);
+ if (value == null) throw new IllegalStateException("Missing environment variable: " + variable);
+ }
+ return value;
+ }
+
+ public EntityMetaFactory entityMetaFactory() {
+ SimpleEntityMetaFactory factory = new SimpleEntityMetaFactory();
+ GeneratedRuntimeModule.module().install(factory);
+ EntityMetaFactory.registerGlobal(factory);
+ return factory;
+ }
+
+ public DataServiceExecutor dataServiceExecutor(
+ JdbcSqlExecutor executor, DataSource dataSource) {
+ return new io.teaql.core.sqlite.SqliteDataServiceExecutor(
+ "default", executor, dataSource);
+ }
+
+ public io.teaql.core.DataServiceRegistry dataServiceRegistry(DataServiceExecutor dataServiceExecutor) {
+ io.teaql.runtime.DefaultDataServiceRegistry registry = new io.teaql.runtime.DefaultDataServiceRegistry();
+ registry.register("default", dataServiceExecutor);
+ return registry;
+ }
+
+ public WorkspaceTeaQLDatabase teaQLDatabase(JdbcSqlExecutor executor, javax.sql.DataSource dataSource) {
+ return new WorkspaceTeaQLDatabase(executor, dataSource);
+ }
+
+ public TeaQLRuntime teaQLRuntime(
+ EntityMetaFactory entityMetaFactory,
+ DataServiceRegistry registry,
+ WorkspaceTeaQLDatabase database) {
+ return TeaQLRuntime.builder()
+ .metadata(entityMetaFactory)
+ .registry(registry)
+ .idGenerationService(new IdSpaceIdGenerator(database))
+ .businessClock(context -> java.time.LocalDate.of(2026, 10, 1))
+ .businessIdInfrastructure(new JdbcBusinessIdAllocator(database))
+ .businessIdKeyProvider(businessIdKeyProvider())
+ .build()
+ .install(GeneratedRuntimeModule.module());
+ }
+
+ private static StaticBusinessIdKeyProvider businessIdKeyProvider() {
+ String encoded = System.getenv("TEAQL_BUSINESS_ID_KEY_V1_HEX");
+ if (encoded == null || encoded.isBlank()) {
+ throw new IllegalStateException(
+ "TEAQL_BUSINESS_ID_KEY_V1_HEX must contain exactly 64 hexadecimal characters");
+ }
+ try {
+ int version = Integer.parseInt(
+ System.getenv().getOrDefault("TEAQL_BUSINESS_ID_KEY_VERSION", "1"));
+ return new StaticBusinessIdKeyProvider(
+ new BusinessIdEncodingKey(version, HexFormat.of().parseHex(encoded)));
+ } catch (RuntimeException error) {
+ throw new IllegalStateException(
+ "Invalid TeaQL Business ID key configuration", error);
+ }
+ }
+}
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/CustomUserContext.java b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/CustomUserContext.java
new file mode 100644
index 000000000..034a5998e
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/CustomUserContext.java
@@ -0,0 +1,26 @@
+
+package com.teaql.purchaseordernumbering;
+
+import org.slf4j.MDC;
+import io.teaql.runtime.DefaultUserContext;
+
+public class CustomUserContext extends DefaultUserContext implements PurchaseOrderNumberingUserContext {
+ public CustomUserContext(io.teaql.runtime.TeaQLRuntime runtime) {
+ super(runtime);
+ }
+ public static final String USER_CONTEXT = "User-Context";
+ public static final String ID_SPACE = "ID_SPACE";
+ public static final String MERCHANT = "merchant";
+ public static final String JOB = "job";
+
+ public void init(Object request) {
+ // String idSpace = getIdSpace();
+ // if (idSpace != null) {
+ // MDC.put(ID_SPACE, idSpace);
+ // }
+ }
+
+ public String getIdSpace() {
+ return null; // getHeader(ID_SPACE);
+ }
+}
\ No newline at end of file
diff --git a/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/PurchaseOrderNumbering.java b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/PurchaseOrderNumbering.java
new file mode 100644
index 000000000..76e913e64
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/PurchaseOrderNumbering.java
@@ -0,0 +1,83 @@
+package com.teaql.purchaseordernumbering;
+
+import com.teaql.purchaseordernumbering.platform.Platform;
+import com.teaql.purchaseordernumbering.purchaseorder.PurchaseOrder;
+import io.teaql.core.RequestIntentException;
+import io.teaql.core.UserContext;
+
+final class PurchaseOrderNumbering {
+ private static final String REJECTED_SUPPLIER = "Unaudited Supplier";
+
+ private PurchaseOrderNumbering() {}
+
+ static void verify(UserContext context, String round) {
+ require(round != null && round.matches("[a-z]+"), "Supply the example round label");
+ Platform platform = Q.platformsWithMinimalFields().withIdIs(1L).limit(1)
+ .comment("Read the bootstrapped procurement platform")
+ .purpose("Associate purchase orders with the procurement platform")
+ .executeForOne(context);
+ require(platform != null, "Procurement platform was not bootstrapped");
+
+ PurchaseOrder first = create(context, platform, "Northwind-" + round);
+ PurchaseOrder second = create(context, platform, "Contoso-" + round);
+ Long firstId = first.getId();
+ var firstNumber = first.getOrderNumber();
+ var secondNumber = second.getOrderNumber();
+ String format = "ORD-20261001-[A-Z0-9]{6}";
+ require(firstNumber != null && secondNumber != null
+ && !firstId.equals(second.getId()) && !firstNumber.equals(secondNumber)
+ && firstNumber.value().matches(format) && secondNumber.value().matches(format),
+ "Expected distinct numbers from the Context business day");
+ first.auditAs("Retry recording Northwind's purchase order").save(context);
+ require(firstId.equals(first.getId()) && firstNumber.equals(first.getOrderNumber()),
+ "Retry changed the purchase order identity");
+
+ for (PurchaseOrder order : new PurchaseOrder[] { first, second }) {
+ var read = Q.purchaseOrders().withOrderNumberIs(order.getOrderNumber()).limit(2)
+ .comment("Read a purchase order by its assigned number")
+ .purpose("Verify the procurement record and allocation").executeForOne(context);
+ require(read != null && read.getId().equals(order.getId())
+ && read.getOrderNumber().equals(order.getOrderNumber())
+ && read.getSupplier().equals(order.getSupplier()),
+ "Typed order-number query returned a different purchase order");
+ }
+
+ var rejected = prepare(context, platform, REJECTED_SUPPLIER);
+ String rejection;
+ try {
+ rejected.auditAs(" ").save(context);
+ throw new IllegalStateException("Unaudited purchase order was accepted");
+ } catch (RequestIntentException error) {
+ require(error.getCode().equals("REQUEST_COMMENT_REQUIRED")
+ && error.getRequestKind().equals("mutation"), "Unexpected intent failure");
+ rejection = error.getCode();
+ }
+ var absent = Q.purchaseOrders().withSupplierIs(REJECTED_SUPPLIER).limit(2)
+ .comment("Look for the unaudited purchase order")
+ .purpose("Prove the rejected operation stored no order").executeForOne(context);
+ require(absent == null, "Unaudited purchase order persisted");
+ System.out.printf("PURCHASE_ORDER_NUMBERING={\"round\":\"%s\",\"firstId\":%d,\"firstNumber\":\"%s\","
+ + "\"secondId\":%d,\"secondNumber\":\"%s\",\"retryNumber\":\"%s\","
+ + "\"rejection\":\"%s\",\"typedReadback\":true}%n",
+ round, firstId, firstNumber.value(), second.getId(), secondNumber.value(),
+ first.getOrderNumber().value(), rejection);
+ }
+
+ private static PurchaseOrder prepare(UserContext context, Platform platform, String supplier) {
+ var order = Q.purchaseOrders().comment("Initialize the purchase order")
+ .purpose("Record a procurement commitment").newEntity(context);
+ order.updatePlatform(platform);
+ order.updateSupplier(supplier);
+ return order;
+ }
+
+ private static PurchaseOrder create(UserContext context, Platform platform, String supplier) {
+ var order = prepare(context, platform, supplier);
+ order.auditAs("Record the approved purchase order").save(context);
+ return order;
+ }
+
+ private static void require(boolean condition, String message) {
+ if (!condition) throw new IllegalStateException(message);
+ }
+}
diff --git a/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/WorkspaceTeaQLDatabase.java b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/WorkspaceTeaQLDatabase.java
new file mode 100644
index 000000000..579fe1990
--- /dev/null
+++ b/examples/business-id-runtime/java-app-console/src/main/java/com/teaql/purchaseordernumbering/WorkspaceTeaQLDatabase.java
@@ -0,0 +1,75 @@
+package com.teaql.purchaseordernumbering;
+
+import io.teaql.core.sql.portable.TeaQLDatabase;
+import io.teaql.dataservice.sql.SqlExecutionAdapter;
+import java.util.List;
+import java.util.Map;
+
+/** SQL bridge used by framework services such as the persistent ID allocator. */
+public final class WorkspaceTeaQLDatabase implements TeaQLDatabase {
+ private final SqlExecutionAdapter executor;
+ private final javax.sql.DataSource dataSource;
+
+ public WorkspaceTeaQLDatabase(SqlExecutionAdapter executor, javax.sql.DataSource dataSource) {
+ this.executor = executor;
+ this.dataSource = dataSource;
+ }
+
+ @Override public List