SAP Build Code and AI-assisted development: what the architect decides
Know what SAP Build Code bundles and what Joule generates in it, then put guardrails and a review gate around AI-generated code before it reaches your pipeline.
SAP Build Code is SAP's environment for professional developers who build apps on SAP BTP in Java or JavaScript. It puts SAP Business Application Studio, the CAP programming model, SAPUI5, SAP Fiori elements and SAP Mobile Services in one place, with Joule as an assistant that writes first drafts (SAP product page, read 27 November 2026).
Joule can turn a sentence into a data model, a service, sample data, business logic, unit tests and a Fiori screen. That is fast. It is also a lot of code that nobody typed and somebody must answer for.
So the architect's question is not "should developers use AI?". They already do, in SAP's tools and in their own. The question is: what has to be true before generated code reaches production? This topic answers that with a short policy, a review gate and one architecture decision.
Calder Pumpworks (a fictional company used throughout this course) has a small apps team. It builds side-by-side apps on BTP, such as the distributor order-status app from CAP in depth for architects. Its next request is a quote desk for spare parts: customer service enters quotes for distributors, with a discount ceiling per sales channel.
With Joule, a developer can have a working first version in an afternoon. The value is real: less boilerplate, faster prototypes to show the business, and junior developers who learn CAP by reading generated code.
The risks are just as concrete:
Code that works and is wrong. Generated logic passes a demo and caps the discount at the wrong number. SAP's own tutorial warns that the code "might be different every time you trigger the prompt" (SAP Developers).
Security by omission. A generated service that names no role is open to every signed-in user. Nothing looks broken.
Data in prompts. SAP's Joule tutorial says conversations go to SAP-hosted large language models and asks you not to put personal data, credentials or confidential information in them (SAP Developers). A developer who pastes a production extract to "get realistic sample data" breaks that rule.
Review debt. More code per day means more code to review per day. If review doesn't scale, quality drops quietly.
None of these is new. AI makes each one cheaper to create, so the controls have to sit where code enters the repository, not in a training slide.
As read on SAP's pages on 27 November 2026. Names, bundles and pricing in this area changed several times in 2025 and 2026, so check them before you sign anything.
SAP Build Code. The product page calls it generative AI-based code development "optimized for Java and JavaScript". Its FAQ lists the parts: SAP Business Application Studio (a browser-based development environment), CAP, SAPUI5, SAP Fiori elements and SAP Mobile Services. It also offers a service center for prebuilt integrations and APIs (product page).
Joule in SAP Build Code. SAP's feature page says Joule generates data models, services, sample data and UI annotations from natural language, creates application logic and generates unit tests (feature page).
Part of the unified SAP Build. SAP now describes a unified SAP Build offering that consolidates application development, automation and low-code UI generation. The same page says SAP Build supports Visual Studio Code and connects to MCP servers, and that SAP Build is included as part of SAP Business Suite (SAP Build).
Outside SAP's editor. SAP announced local MCP servers for SAP Build in November 2025, for coding assistants such as Cursor, Windsurf, Claude Code, Cline and OpenAI Codex, plus an SAP Build extension pack for VS Code (SAP News, 5 November 2025). In plain words: your developers can get SAP's generators in the editor and AI assistant they already use.
How it is sold is not settled across SAP's pages. The Joule feature page says full-stack generation is included with Joule Base at no additional cost and needs a Joule Base subscription. The Joule for developers page describes free access for developers using SAP Build after accepting the SAP AI Terms. The SAP Build pricing page (Denmark, in euros) lists an SAP Build developer user at EUR 40.00 per active user per month that includes Joule for developers (pricing). Ask your SAP account team which terms apply to your contract, in writing.
Calder's apps team adopted these eight rules. They are course rules, not SAP's, but each one answers a risk above. The deep layer turns them into an automated gate.
Rule
What it says
Why
G01 Roles
Every service names the role that may use it
Generated services are open by default
G02 Secrets
No credentials in the repository
Generated setups often contain local keys
G03 Certificates
Certificate checks stay on
A quick fix for a self-signed certificate turns off security for everything
G04 Sample data
Sample data matches the model and is made up
Generated data drifts from the model; real data must never be the template
G05 Tests
Business rules live in one place and have tests
You can't review a rule you can't test
G06 Tools
Only approved AI tool servers, at fixed versions
A tool server runs code on the developer's machine
G07 Provenance
Every file says who or what made it, and who reviewed it
Accountability for code nobody typed
G08 Agent rules
The project tells coding agents its rules
Agents follow the instructions they are given
The policy applies the same way whichever editor the developer uses. That is the point: Calder governs what reaches the repository, not which button produced it.
"Generated code is SAP code, so SAP supports it." Once generated, it is your code. SAP's tutorial tells you to verify important details before acting on them.
"Joule only works inside SAP Business Application Studio." As of November 2026, SAP Build also supports VS Code and MCP servers for other coding assistants.
"If the app runs, the generation worked." Running is the lowest bar. Missing roles, wrong limits and untested rules all run fine.
"We'll govern AI by choosing one tool." Developers switch tools. A gate on the repository outlasts any tool decision.
"AI-assisted development is free." Some SAP pages say so; others put Joule for developers in a paid developer user. Check your contract.
SAP Build Code: SAP's environment for Java and JavaScript development on SAP BTP, bundling SAP Business Application Studio, CAP, SAPUI5, SAP Fiori elements and SAP Mobile Services, with Joule.
SAP Business Application Studio: SAP's browser-based development environment, organized in dev spaces.
Joule for developers: SAP's name for the AI capabilities in its development tools, for SAP Build and ABAP.
MCP server: a program that offers tools to an AI assistant through the Model Context Protocol; SAP publishes several for its development stacks.
Review gate: an automated check that must pass before code is merged or deployed.
Provenance record: a list saying which files a model generated, from what request, and who reviewed them.
Pick one answer for each question. The explanation appears after you choose.
1What is the architect's main question about AI-generated code?
Answer: A. Developers already use AI in SAP's tools and their own. The useful decision is the bar generated code must pass before production. Tool choice changes; the bar stays.
2Why does Calder govern the repository instead of picking one AI tool?
Answer: C. SAP Build now works in Business Application Studio and in VS Code with MCP servers for other assistants. Whatever produced the code, it has to pass the same gate where it enters the repository.
3A developer wants realistic sample data and plans to paste a production customer extract into Joule. What should happen?
Answer: C. SAP's tutorial says conversations go to SAP-hosted large language models and asks you not to include personal data, credentials or confidential information. Sample data is generated or made up, never copied from production.
4A generated quote service runs and the demo works. Which risk is still most likely open?
Answer: B. Missing roles don't break anything visible, so a demo doesn't reveal them. That is why the policy's first rule asks every service to name the role that may use it.
5How should a leader treat SAP's pricing for Joule in SAP Build Code as of November 2026?
Answer: A. SAP's pages describe three different models on the same day: free under the SAP AI Terms, included with Joule Base, and in a paid developer user. Only your account team can say which applies to you.
6What does a provenance record add that a passing build doesn't?
Answer: B. Months later, someone has to answer for the code. The record says what was generated and who reviewed it. It can't make generation repeatable, because the same prompt can give different code.
Treat an AI assistant as a very fast junior developer who never remembers your project's rules unless you write them down, and who doesn't sign their work.
Three consequences follow. You give it written rules (an AGENTS.md file and approved tools). You check its output with the same tests and reviews as anyone's, automated where possible because there will be a lot of it. And you record what it did, because it won't.
None of that depends on the tool. Joule in SAP Business Application Studio, an SAP MCP server driven by another assistant in VS Code, or a coding agent from Coding agents for SAP developers: all three produce files in a repository. The gate sits at the repository. SAP Build Code is one good place to generate; it is not where governance happens.
As described on SAP's pages read on 27 November 2026, a CAP project in SAP Build Code goes through these steps:
Start in the SAP Build lobby. SAP's tutorial chooses Create, Build an Application, the SAP Build Code tile, then Full-Stack Application. The project opens in SAP Business Application Studio (SAP Developers).
Ask Joule. Joule opens from the activity bar. SAP's tutorial uses slash commands for the steps: /cap-gen-app, /cap-gen-model for the data model, /cap-gen-data and /cap-edit-data for sample data, and /cap-app-logic for handlers (SAP Developers).
Generate the UI. The tutorial adds SAP Fiori elements list report pages and previews them.
Leave the editor. From here the project is ordinary CAP: files in Git, built and deployed by a pipeline. SAP's managed option is SAP Continuous Integration and Delivery, which runs predefined pipelines from a Git repository and can hand the result to SAP Cloud Transport Management (product page). Pipelines and transports have their own topic later in Unit 21.
The same project can be built outside SAP's editor. SAP's SAP Build Full-Stack Extension Pack for VS Code bundles the full-stack tools, and a Service Catalog extension brings the service center to VS Code, starting with the ABAP catalog and on-premise systems (SAP Community). MCP servers give other assistants SAP's generators: the Fiori MCP server, for example, has tools such as generate_fiori_app_cap and list_sap_systems (README).
flowchart LR
subgraph Generate
J[Joule in Business<br/>Application Studio]
V[VS Code + assistant<br/>+ SAP MCP servers]
end
J --> R[Git repository]
V --> R
R --> G[Review gate<br/>G01-G08]
G -->|pass| P[Pull request review<br/>by a person]
P --> C[CI/CD pipeline<br/>build, test, deploy]
C --> T[Cloud Transport<br/>Management]
T --> Q[Test, then<br/>production subaccount]
G -->|fail| X[Back to the developer]
Two details matter for the architecture.
Where prompts go. SAP's tutorial says Joule's conversations are sent to SAP-hosted large language models. The Joule for developers page lists third-party foundation models (OpenAI, PaLM 2, Gemini, Anthropic, Llama, Mistral AI) next to SAP's own ABAP model (Joule for developers). A third-party assistant in VS Code sends prompts to its own provider instead. Each route needs its own data-protection check.
What a tool server can do. A local MCP server is a program running on the developer's machine with the developer's rights. The Fiori MCP server README recommends pinning its version so untested updates aren't picked up, says telemetry is on by default and how to turn it off, and warns against NODE_TLS_REJECT_UNAUTHORIZED=0, which turns off certificate checks. SAP's MDK MCP server says its tools "do not constitute a stable API" (GitHub). Treat these servers like any other dependency: approved, pinned and reviewed. AI supply-chain controls shows why.
#Build it yourself: a review gate for generated code
You will write a small Python script that checks a CAP project against Calder's eight rules. It first creates the kind of project a quick Joule session can leave behind, finds seven problems in it, then checks the reviewed version. Point it at your own generated project afterwards. It runs on your computer with no account and no SAP system.
flowchart LR
I[--init] --> D[sq-app<br/>the draft]
D --> G[genai_code_gate.py<br/>rules G01-G08]
W[--reviewed] --> RV[sq-app-reviewed]
RV --> G
G --> O[OK / WARN / FAIL<br/>exit code 0 or 2]
G --> RP[--report<br/>gate_report.md]
In VS Code, create a new file unit21/genai_code_gate.py.
Paste the whole script below and save. It uses built-in Python modules only, so there is nothing to install and nothing to add to requirements.txt.
"""A review gate for AI-generated CAP projects, such as a first draft from Joule in SAP Build Code.
Unit 21, SAP Build Code and AI-assisted development. Built-in modules only, no randomness.
python unit21/genai_code_gate.py --init write Calder's draft project to unit21/genai/sq-app
python unit21/genai_code_gate.py check unit21/genai/sq-app against rules G01-G08
python unit21/genai_code_gate.py --reviewed write the reviewed project to unit21/genai/sq-app-reviewed
python unit21/genai_code_gate.py --path DIR check any CAP project folder (your own Joule output too)
python unit21/genai_code_gate.py --report also write unit21/genai/gate_report.md
Exit code 2 when any rule FAILs, so a pipeline can stop on it.
The rules, the app, people and numbers are course values. Calder Pumpworks is fictional.
"""
import argparse
import json
import re
import sys
from pathlib import Path
BASE = Path("unit21") / "genai"
DRAFT = BASE / "sq-app"
REVIEWED = BASE / "sq-app-reviewed"
# MCP servers the team has approved (course list). Each must be pinned to an exact version.
APPROVED_MCP = {"@sap-ux/fiori-mcp-server", "@cap-js/mcp-server", "@sap/mdk-mcp-server"}
SECRET_WORDS = ("clientsecret", "client_secret", "password", "apikey", "api_key")
SOURCE_DIRS = ("db", "srv", "app")
SOURCE_EXT = {".cds", ".js", ".csv", ".json"}
# ---------------------------------------------------------------------------
# Calder's draft: what a first Joule session could plausibly leave behind.
# ---------------------------------------------------------------------------
SCHEMA = """namespace calder.quotes;
using { managed } from '@sap/cds/common';
// Spare part quotes for distributors (Calder's service quote desk).
entity Quotes : managed {
key ID : Integer;
customer : String(10);
channel : String(2);
status : String(1);
validTo : Date;
netAmount : Decimal(15,2);
items : Composition of many QuoteItems on items.quote = $self;
}
entity QuoteItems {
key ID : Integer;
quote : Association to Quotes;
material : String(40);
quantity : Integer;
unitPrice : Decimal(15,2);
discountPct : Decimal(5,2);
}
"""
DRAFT_FILES = {
"db/schema.cds": SCHEMA,
"db/data/calder.quotes-Quotes.csv": (
"ID;customer;channel;status;validTo;netAmount;contactEmail\n"
"1;10000002;20;O;2026-12-31;1710.00;orders@hallam-fluid.example\n"
"2;10000001;10;O;2026-12-31;1520.00;m.adler@brennock-water.example\n"),
"db/data/calder.quotes-QuoteItems.csv": (
"ID;quote_ID;material;quantity;unitPrice;discountPct\n"
"1;1;CP-SK200;20;95.00;10\n"
"2;2;CP-SK200;16;95.00;0\n"),
"srv/quote-service.cds": (
"using calder.quotes as q from '../db/schema';\n\n"
"service QuoteService {\n"
" entity Quotes as projection on q.Quotes;\n"
" entity QuoteItems as projection on q.QuoteItems;\n"
"}\n"),
"srv/quote-service.js": (
"import cds from '@sap/cds'\n\n"
"export default class QuoteService extends cds.ApplicationService {\n"
" async init() {\n"
" const { QuoteItems } = this.entities\n"
" // Generated from the prompt: distributors get at most 15% off.\n"
" this.before('CREATE', QuoteItems, req => {\n"
" if (req.data.discountPct > 15) req.data.discountPct = 15\n"
" })\n"
" return super.init()\n"
" }\n"
"}\n"),
"package.json": json.dumps({
"name": "sq-app", "version": "1.0.0", "type": "module",
"dependencies": {"@sap/cds": "^10"},
"scripts": {"watch": "NODE_TLS_REJECT_UNAUTHORIZED=0 cds watch"}}, indent=2) + "\n",
"default-env.json": json.dumps({"VCAP_SERVICES": {"xsuaa": [{"credentials": {
"clientid": "sb-sq-app", "clientsecret": "s3cr3t-from-the-dev-space"}}]}}, indent=2) + "\n",
".mcp.json": json.dumps({"mcpServers": {
"fiori-mcp": {"command": "npx",
"args": ["--yes", "@sap-ux/fiori-mcp-server@latest", "fiori-mcp"]},
"erp-tools": {"command": "npx", "args": ["-y", "@example/erp-tools"]}}}, indent=2) + "\n",
"AGENTS.md": (
"# Rules for coding agents in this project\n\n"
"- Use the Fiori MCP server, if available, to generate or change Fiori apps.\n"
"- Change the project's code, not screen personalization.\n"),
}
# The reviewed project: the same app after a person went through the gate's findings.
REVIEWED_FILES = dict(DRAFT_FILES)
del REVIEWED_FILES["default-env.json"]
REVIEWED_FILES.update({
"db/data/calder.quotes-Quotes.csv": (
"ID;customer;channel;status;validTo;netAmount\n"
"1;10000002;20;O;2026-12-31;1710.00\n"
"2;10000001;10;O;2026-12-31;1520.00\n"),
"srv/quote-service.cds": (
"using calder.quotes as q from '../db/schema';\n\n"
"service QuoteService @(requires: 'QuoteClerk') {\n"
" entity Quotes as projection on q.Quotes;\n"
" entity QuoteItems as projection on q.QuoteItems;\n"
"}\n"),
"srv/lib/discount.js": (
"// Calder's discount ceiling by sales channel (course values).\n"
"export const MAX_DISCOUNT = { '10': 5, '20': 15 }\n\n"
"export function capDiscount(pct, channel) {\n"
" const max = MAX_DISCOUNT[channel] ?? 0\n"
" return Math.min(Math.max(pct ?? 0, 0), max)\n"
"}\n"),
"srv/quote-service.js": (
"import cds from '@sap/cds'\n"
"import { capDiscount } from './lib/discount.js'\n\n"
"export default class QuoteService extends cds.ApplicationService {\n"
" async init() {\n"
" const { Quotes, QuoteItems } = this.entities\n"
" this.before('CREATE', QuoteItems, async req => {\n"
" const quote = await SELECT.one.from(Quotes, req.data.quote_ID)\n"
" req.data.discountPct = capDiscount(req.data.discountPct, quote?.channel)\n"
" })\n"
" return super.init()\n"
" }\n"
"}\n"),
"test/discount.test.js": (
"// Run with: node --test (Node.js 22 or later; no CAP install needed for this file)\n"
"import { test } from 'node:test'\n"
"import assert from 'node:assert/strict'\n"
"import { capDiscount } from '../srv/lib/discount.js'\n\n"
"test('distributors get at most 15%', () => assert.equal(capDiscount(20, '20'), 15))\n"
"test('direct customers get at most 5%', () => assert.equal(capDiscount(10, '10'), 5))\n"
"test('unknown channel gets none', () => assert.equal(capDiscount(10, '30'), 0))\n"
"test('negative becomes zero', () => assert.equal(capDiscount(-3, '20'), 0))\n"),
"package.json": json.dumps({
"name": "sq-app", "version": "1.0.0", "type": "module",
"dependencies": {"@sap/cds": "^10"},
"scripts": {"watch": "cds watch", "test": "node --test"}}, indent=2) + "\n",
".gitignore": "node_modules/\n.env\ndefault-env.json\n",
".mcp.json": json.dumps({"mcpServers": {
"fiori-mcp": {"command": "npx",
"args": ["--yes", "@sap-ux/fiori-mcp-server@1.12.2", "fiori-mcp"]}}},
indent=2) + "\n",
"AGENTS.md": DRAFT_FILES["AGENTS.md"] + (
"- Never put credentials, personal data or customer documents in a prompt.\n"
"- Put business rules in srv/lib and add a test in test/ for each one.\n"
"- Record every generated file in AI-PROVENANCE.md; a person reviews it before merge.\n"),
"AI-PROVENANCE.md": (
"# AI provenance\n\n"
"| File | Made by | Prompt or note | Reviewer | Reviewed on |\n"
"| --- | --- | --- | --- | --- |\n"
"| db/schema.cds | Joule | Quotes with items for distributors | 00100288 | 2026-11-27 |\n"
"| db/data/calder.quotes-Quotes.csv | Joule | Two sample quotes; email column removed | 00100288 | 2026-11-27 |\n"
"| db/data/calder.quotes-QuoteItems.csv | Joule | Sample items | 00100288 | 2026-11-27 |\n"
"| srv/quote-service.cds | Joule | Service; role added by reviewer | 00100288 | 2026-11-27 |\n"
"| srv/quote-service.js | Joule | Handler; rule moved to srv/lib | 00100288 | 2026-11-27 |\n"
"| srv/lib/discount.js | Person | Ceiling per channel from the pricing analyst | 00100292 | 2026-11-27 |\n"),
})
def write_project(target, files):
for rel, text in files.items():
p = target / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8", newline="\n")
print(f"Wrote {len(files)} files to {target.as_posix()}")
# ---------------------------------------------------------------------------
# Reading the project
# ---------------------------------------------------------------------------
def files_in(root):
return sorted(p for p in root.rglob("*")
if p.is_file() and "node_modules" not in p.parts and ".git" not in p.parts)
def rel(root, p):
return p.relative_to(root).as_posix()
def cds_entities(root):
"""Return {qualified entity name: set of column names a CSV may use} from db/*.cds."""
out = {}
for f in (root / "db").glob("*.cds"):
text = re.sub(r"//.*", "", f.read_text(encoding="utf-8"))
ns = re.search(r"namespace\s+([\w.]+)\s*;", text)
prefix = ns.group(1) + "." if ns else ""
for m in re.finditer(r"entity\s+(\w+)\s*(?::\s*([\w,\s]+))?\{(.*?)\}", text, re.S):
name, mixins, body = m.group(1), m.group(2) or "", m.group(3)
cols = set()
if "managed" in mixins:
cols |= {"createdAt", "createdBy", "modifiedAt", "modifiedBy"}
if "cuid" in mixins:
cols.add("ID")
for line in body.split(";"):
el = re.match(r"\s*(?:key\s+)?(\w+)\s*:\s*(.+)", line, re.S)
if not el:
continue
ename, etype = el.group(1), el.group(2)
if etype.strip().startswith("Composition"):
continue
if etype.strip().startswith("Association"):
cols.add(ename + "_ID")
else:
cols.add(ename)
out[prefix + name] = {"cols": cols, "mixins": mixins, "body": body}
return out
# ---------------------------------------------------------------------------
# Rules G01-G08 (course rules)
# ---------------------------------------------------------------------------
def check(root):
findings = []
add = lambda rule, verdict, text: findings.append((rule, verdict, text))
all_files = files_in(root)
texts = {rel(root, p): p.read_text(encoding="utf-8", errors="replace") for p in all_files}
# G01 every service names who may use it
services = []
for name, text in texts.items():
if name.startswith("srv/") and name.endswith(".cds"):
for m in re.finditer(r"service\s+(\w+)\s*(@\([^)]*\))?\s*\{", text):
services.append((name, m.group(1), m.group(2) or ""))
if not services:
add("G01", "WARN", "no service found in srv/*.cds")
for name, svc, ann in services:
before = texts[name][:texts[name].find("service " + svc)]
if "requires" in ann or "restrict" in ann or re.search(r"@(requires|restrict)\s*:\s*[^\n]*\s*$", before):
add("G01", "OK", f"{svc} names a role ({name})")
else:
add("G01", "FAIL", f"{svc} has no @requires or @restrict: any signed-in user can use it ({name})")
# G02 no secrets in the project, and the usual secret files are ignored by Git
leaks = [n for n, t in texts.items()
if n not in (".env.example",)
and any(re.search(rf'"?{w}"?\s*[:=]\s*"?[^"\s,}}]{{4,}}', t, re.I) for w in SECRET_WORDS)]
ignore = texts.get(".gitignore", "")
missing = [x for x in (".env", "default-env.json") if x not in ignore.split()]
if leaks:
add("G02", "FAIL", "secret values in " + ", ".join(leaks))
elif missing:
add("G02", "WARN", ".gitignore doesn't list " + ", ".join(missing))
else:
add("G02", "OK", "no secret values; .env and default-env.json ignored by Git")
# G03 TLS certificate checks stay on
tls = [n for n, t in texts.items() if re.search(r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['\"]?0", t)]
if tls:
add("G03", "FAIL", "NODE_TLS_REJECT_UNAUTHORIZED=0 turns off certificate checks in " + ", ".join(tls))
else:
add("G03", "OK", "certificate checks not turned off")
# G04 sample data fits the model
ents = cds_entities(root)
csvs = [n for n in texts if n.startswith("db/data/") and n.endswith(".csv")]
if not csvs:
add("G04", "OK", "no sample data")
for n in csvs:
entity = Path(n).stem.replace("-", ".")
header_line = texts[n].splitlines()[0] if texts[n].strip() else ""
sep = ";" if header_line.count(";") >= header_line.count(",") else ","
header = [h.strip() for h in header_line.split(sep) if h.strip()]
if entity not in ents:
add("G04", "FAIL", f"{n}: no entity {entity} in db/*.cds")
continue
extra = [h for h in header if h not in ents[entity]["cols"]]
if extra:
add("G04", "FAIL", f"{n}: columns not in the model: {', '.join(extra)}")
else:
add("G04", "OK", f"{n}: {len(header)} columns, all in {entity}")
# G05 business rules live in srv/lib and each lib module has a test
handlers = [n for n in texts if re.fullmatch(r"srv/[^/]+\.js", n)]
libs = [n for n in texts if n.startswith("srv/lib/") and n.endswith(".js")]
tests = {n: t for n, t in texts.items() if n.startswith("test/") and n.endswith(".js")}
for h in handlers:
if "./lib/" in texts[h]:
add("G05", "OK", f"{h} takes its rules from srv/lib")
else:
add("G05", "FAIL", f"{h} holds its rules inline; move them to srv/lib and test them there")
for lib in libs:
stem = Path(lib).stem
if any(re.search(rf"lib/{re.escape(stem)}(\.js)?['\"]", t) for t in tests.values()):
add("G05", "OK", f"{lib} has a test")
else:
add("G05", "FAIL", f"{lib} has no test in test/")
# G06 MCP servers: approved and pinned to an exact version
for cfg in (".mcp.json", ".vscode/mcp.json"):
if cfg not in texts:
continue
data = json.loads(texts[cfg])
servers = data.get("mcpServers") or data.get("servers") or {}
for sname, s in servers.items():
pkg = next((a for a in s.get("args", []) if not a.startswith("-")), "")
m = re.fullmatch(r"(@?[^@]+)(?:@(.+))?", pkg)
pname, ver = (m.group(1), m.group(2)) if m else (pkg, None)
if pname not in APPROVED_MCP:
add("G06", "FAIL", f"{cfg}: {sname} runs {pname}, which isn't on the approved list")
elif not ver or not re.fullmatch(r"\d+\.\d+\.\d+", ver):
add("G06", "FAIL", f"{cfg}: {sname} isn't pinned to an exact version ({pkg})")
else:
add("G06", "OK", f"{cfg}: {sname} {pname} {ver}")
# G07 provenance: every source file listed, with a reviewer
sources = [n for n in texts if n.split("/")[0] in SOURCE_DIRS and Path(n).suffix in SOURCE_EXT]
prov = texts.get("AI-PROVENANCE.md")
if prov is None:
add("G07", "FAIL", "no AI-PROVENANCE.md: nobody can tell which files a model wrote or who reviewed them")
else:
rows = [[c.strip() for c in line.strip().strip("|").split("|")]
for line in prov.splitlines() if line.startswith("|") and not line.startswith("| ---")][1:]
listed = {r[0]: r for r in rows if r}
unlisted = [s for s in sources if s not in listed]
gone = [f for f in listed if f not in texts]
unreviewed = [f for f, r in listed.items() if len(r) < 4 or not re.fullmatch(r"\d{8}", r[3])]
if unlisted or gone or unreviewed:
parts = []
if unlisted: parts.append("not listed: " + ", ".join(unlisted))
if gone: parts.append("listed but missing: " + ", ".join(gone))
if unreviewed: parts.append("no reviewer: " + ", ".join(unreviewed))
add("G07", "FAIL", "; ".join(parts))
else:
add("G07", "OK", f"{len(listed)} files listed, each with a reviewer")
# G08 instructions for coding agents
if "AGENTS.md" in texts:
add("G08", "OK", "AGENTS.md gives coding agents the project's rules")
else:
add("G08", "WARN", "no AGENTS.md: agents start without the project's rules")
return findings
def summarize(root, findings):
print(f"Gate for {root.as_posix()}")
for rule, verdict, text in findings:
print(f" {rule} {verdict:<4} {text}")
rules = sorted({r for r, _, _ in findings})
worst = {}
order = {"OK": 0, "WARN": 1, "FAIL": 2}
for r, v, _ in findings:
worst[r] = max(worst.get(r, "OK"), v, key=order.get)
counts = {v: sum(1 for r in rules if worst[r] == v) for v in ("OK", "WARN", "FAIL")}
print(f"{len(rules)} rules: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
return counts
def write_report(root, findings, counts):
out = BASE / "gate_report.md"
out.parent.mkdir(parents=True, exist_ok=True)
lines = [f"# Generated code review: {root.as_posix()}", "",
f"Result: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL", "",
"| Rule | Verdict | Finding |", "| --- | --- | --- |"]
lines += [f"| {r} | {v} | {t} |" for r, v, t in findings]
lines += ["", "## Decision record", "", "- Context:", "- Options:", "- Decision:", "- Consequences:", ""]
out.write_text("\n".join(lines), encoding="utf-8")
print(f"Wrote {out.as_posix()}")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--init", action="store_true", help="write the draft project")
ap.add_argument("--reviewed", action="store_true", help="write the reviewed project")
ap.add_argument("--path", help="project folder to check (default: the draft)")
ap.add_argument("--report", action="store_true", help="write unit21/genai/gate_report.md")
a = ap.parse_args()
if a.init:
write_project(DRAFT, DRAFT_FILES)
return 0
if a.reviewed:
write_project(REVIEWED, REVIEWED_FILES)
return 0
root = Path(a.path) if a.path else DRAFT
if not root.is_dir():
print(f"{root.as_posix()} not found. Run: python unit21/genai_code_gate.py --init")
return 1
findings = check(root)
counts = summarize(root, findings)
if a.report:
write_report(root, findings, counts)
return 2 if counts["FAIL"] else 0
if __name__ == "__main__":
sys.exit(main())
Write the draft. It stands in for a first Joule session on Calder's spare-part quote desk:
python unit21/genai_code_gate.py --init
Wrote 9 files to unit21/genai/sq-app
Run the gate:
python unit21/genai_code_gate.py
Expected output:
Gate for unit21/genai/sq-app
G01 FAIL QuoteService has no @requires or @restrict: any signed-in user can use it (srv/quote-service.cds)
G02 FAIL secret values in default-env.json
G03 FAIL NODE_TLS_REJECT_UNAUTHORIZED=0 turns off certificate checks in package.json
G04 OK db/data/calder.quotes-QuoteItems.csv: 6 columns, all in calder.quotes.QuoteItems
G04 FAIL db/data/calder.quotes-Quotes.csv: columns not in the model: contactEmail
G05 FAIL srv/quote-service.js holds its rules inline; move them to srv/lib and test them there
G06 FAIL .mcp.json: fiori-mcp isn't pinned to an exact version (@sap-ux/fiori-mcp-server@latest)
G06 FAIL .mcp.json: erp-tools runs @example/erp-tools, which isn't on the approved list
G07 FAIL no AI-PROVENANCE.md: nobody can tell which files a model wrote or who reviewed them
G08 OK AGENTS.md gives coding agents the project's rules
8 rules: 1 OK, 0 WARN, 7 FAIL
Open unit21/genai/sq-app in the VS Code explorer and look at the files behind each finding. Nothing there is exotic: an open service, a local credentials file, a certificate shortcut, a sample-data column the model doesn't have, a discount ceiling buried in a handler, an unpinned and an unknown tool server, and no record of what was generated.
Gate for unit21/genai/sq-app-reviewed
G01 OK QuoteService names a role (srv/quote-service.cds)
G02 OK no secret values; .env and default-env.json ignored by Git
G03 OK certificate checks not turned off
G04 OK db/data/calder.quotes-QuoteItems.csv: 6 columns, all in calder.quotes.QuoteItems
G04 OK db/data/calder.quotes-Quotes.csv: 6 columns, all in calder.quotes.Quotes
G05 OK srv/quote-service.js takes its rules from srv/lib
G05 OK srv/lib/discount.js has a test
G06 OK .mcp.json: fiori-mcp @sap-ux/fiori-mcp-server 1.12.2
G07 OK 6 files listed, each with a reviewer
G08 OK AGENTS.md gives coding agents the project's rules
8 rules: 8 OK, 0 WARN, 0 FAIL
Wrote unit21/genai/gate_report.md
Open unit21/genai/sq-app-reviewed/AI-PROVENANCE.md. Each file names who made it (Joule or a person), what the request was, and the reviewer's personnel number: 00100288, Calder's integration developer, and 00100292, the integration lead, who wrote the discount rule by hand from the pricing analyst's table.
#Step 6: Run the reviewed project's tests (optional, needs Node.js)
The discount rule now lives in srv/lib/discount.js, a plain function, so it can be tested without starting CAP.
Go into the reviewed project:
Windows (PowerShell):
cd unit21\genai\sq-app-reviewed
macOS / Linux:
cd unit21/genai/sq-app-reviewed
Run Node's built-in test runner:
node --test
The last lines should include:
# tests 4
# pass 4
# fail 0
Go back: cd ../../..
If you also have the CAP tools from Set up for Unit 5, npm install and cds watch in this folder start the app. A request without the QuoteClerk role is then refused with 403, because of the role G01 asked for.
#Step 7: Point the gate at your own project (optional)
If you generate a CAP project with Joule, on SAP's trial or your company's tenant, or with an assistant and SAP's MCP servers in VS Code, download or clone it into your course folder and run:
Expect FAILs on G06 to G08 at first: a fresh project has no provenance record and may have no tool configuration at all. The gate only reads files; it never changes your project. Check that SAP's trial still offers SAP Build Code before you rely on it: the tutorial that uses it was last updated in November 2024.
The two sample projects as text, written by --init and --reviewed
cds_entities()
Reads db/*.cds with simple patterns and returns each entity's columns, including managed fields and association keys such as quote_ID
check()
Applies G01 to G08 and returns a list of (rule, verdict, finding)
G06 block
Reads .mcp.json or .vscode/mcp.json, takes the package from the npx arguments, and checks it against APPROVED_MCP and an exact x.y.z version
G07 block
Reads the table in AI-PROVENANCE.md; every file under db, srv and app must be listed, exist and have an 8-digit reviewer
summarize()
Prints each finding and counts each rule by its worst verdict
main()
Returns exit code 2 if any rule fails, so a pipeline step fails too
The CDS reading is deliberately simple. It handles the flat entities in this project, not every CDS feature. A real gate would compile the model with the CAP tools and inspect the result, as the review script in CAP in depth for architects does.
What SAP Build Code bundles. SAP Business Application Studio, CAP, SAPUI5, SAP Fiori elements and SAP Mobile Services, with a service center for prebuilt integrations, APIs and business services (product page).
What Joule generates in it. Data models, services, sample data and UI annotations from natural language; application logic; unit tests (feature page). SAP's tutorials add the slash commands and the Fiori elements screens, and warn that generative AI "may produce inaccurate, incomplete, or biased information" (SAP Developers).
Getting it. SAP's tutorials start from the SAP Build lobby on an SAP BTP trial account. A customer that already runs SAP Business Application Studio on the standard plan can update the subscription to the build-code plan in Instances and Subscriptions; projects from before stay reachable through the Dev Space Manager (SAP Community).
Licensing. Three statements, all read today. The feature page: included with Joule Base at no additional cost, Joule Base subscription required. The Joule for developers page: free for developers using SAP Build after accepting the SAP AI Terms, enabled by default when you sign up for SAP Build Code. The SAP Build pricing page (Denmark, EUR): SAP Build developer at EUR 40.00 per active user per month, including Joule for developers, Joule Studio and low-code and code-first tools; SAP Build runtime at EUR 1.00 per capacity unit, including the Cloud Foundry, ABAP and Kyma runtimes, CI/CD and cloud transport management. The SAP Build page says SAP Build is included as part of SAP Business Suite and that entitlements show in the SAP BTP cockpit.
VS Code and other assistants. SAP Build supports VS Code and connects to MCP servers (SAP Build page). SAP News (5 November 2025) announced local MCP servers for SAP Build and an SAP Build extension pack for VS Code, and said the extensions would be published on the Open VSX Registry (SAP News). The CAP MCP server is covered in Coding agents for SAP developers.
Joule Studio, next door. At SAP TechEd on 27 October 2026, SAP said Joule Studio is reached through Joule Work, offers no-code and pro-code tools with more than 70 AI models, and that design-time tooling including AI-assisted development stays free under fair-use limits (SAP News). Joule Studio builds agents and Joule skills; SAP Build Code builds applications. Joule and Joule Studio covers the agent side.
Pipelines. SAP Continuous Integration and Delivery runs predefined pipelines from your Git repository and can upload the result to SAP Cloud Transport Management, billed in compute hours (product page). A gate like the one above runs as an extra step in whatever pipeline you use.
Where it sits. Generation happens on developers' machines or in SAP Business Application Studio dev spaces in the Extensions directory's development subaccount (from the BTP account model). Code goes to Git; the pipeline builds, tests and deploys to the test and production subaccounts. The flow diagram in How it works shows the path.
Non-functional requirements.
Requirement
Typical target at Calder
What breaks if missed
Security of generated code
Gate passes on every merge; one person reviews every pull request
Open services and missing checks reach production
Data protection
No personal or confidential data in prompts; approved model routes only
Customer data with a third-party model provider
Supply chain
Approved tool servers at exact versions
An update or unknown package runs on developer machines
Traceability
Provenance for every file under db, srv, app
Nobody can answer for code in an audit
Cost
Developer licences known per person; review time budgeted
Surprise bills, or reviews skipped to keep pace
Integration and identity. Generated apps reach S/4HANA through destinations, covered in Connectivity, and their roles come from the BTP security model. The assistant itself must never hold production credentials. Developers generate against sandbox or development systems only. The Fiori MCP server has a list_sap_systems tool, so an assistant can see the SAP systems the developer has set up; production shouldn't be among them.
Context: Calder's apps team uses Joule in SAP Business Application Studio; two employees also use VS Code with another assistant; contractors join for projects; SAP's licensing pages disagree.
Options: A) SAP Business Application Studio with Joule only, other assistants banned; B) any editor and assistant, no shared rules; C) any approved editor, with one repository gate (G01 to G08), approved and pinned MCP servers, and dev spaces for contractors.
Decision: C.
Consequences: the gate runs as a pipeline step and blocks merges on FAIL; the integration lead owns the approved tool list; contractors work only in dev spaces; licensing is confirmed in writing before the team grows.
What a design review will ask.
Where do prompts go for each assistant in use, and what may never be in them?
What stops a generated service without roles from reaching production?
Who approves an MCP server, and how is its version fixed?
How do we tell generated code from written code, and who reviewed it?
What happens to review capacity when generation doubles the code volume?
Security and SAP authorizations. Generated code gets the same checks as written code: roles on every service, row filters for partner data, no secrets in Git. The gate catches the obvious cases; the human reviewer reads the logic.
Evaluation. Measure the gate, not the model: how many generated pull requests fail which rule, and how often a reviewer finds something the gate missed. Rising G05 failures mean rules are being generated faster than tested.
Cost. Licences per developer (check your terms), BTP runtime, and reviewer time. Reviewer time is the one that grows with AI.
Operations. Treat MCP servers and extensions as dependencies with owners, versions and an update rhythm. Turn off telemetry where your policy requires it; the Fiori MCP server README shows how.
Clean core. Joule generates side-by-side CAP apps on BTP, which keeps logic out of S/4HANA. That holds only if the apps call released APIs; review generated calls for that, as in Fit-to-standard and extension choices.
A delivered SAP capability. Joule in SAP Build Code is AI-assisted development as a product feature. Use it for drafts, then review.
An agent as one more developer. With SAP's MCP servers, a coding agent can create Fiori apps and CAP artifacts itself. Give it written rules (AGENTS.md), approved tools and a gate, as in Coding agents for SAP developers.
Intent first. For agents and Joule skills, SAP's intent-based approach in Joule Studio starts from a written intent and tests, covered in Intent-based development with Joule Studio.
Governing the tool, not the output. A ban on one assistant moves developers to another; a gate on the repository covers all of them.
Accepting generated sample data unread. Columns that don't fit the model, or data that looks too real, are signs that something went into a prompt that shouldn't have.
Unpinned tool servers.@latest means tomorrow's code runs with today's approval.
Rules inside handlers. Logic mixed into event handlers can't be tested alone, so it isn't.
Planning on "free". SAP's pages disagree on what AI-assisted development costs. Get your terms in writing before the team relies on it.
Letting the gate replace the review. The gate finds what rules can find. A person still reads the logic.
Add a ninth rule to the gate, fix the reviewed project so it passes, and keep the report for the capstone pack.
Open unit21/genai_code_gate.py.
Find the line add("G08", "WARN", "no AGENTS.md: agents start without the project's rules"). Directly below it, before return findings, add this block (same indentation as the # G08 comment):
# G09 keys are UUIDs (cuid)
for name, e in ents.items():
if "cuid" in e["mixins"]:
add("G09", "OK", f"{name} uses cuid")
else:
add("G09", "FAIL", f"{name} has its own key; use cuid for UUID keys")
Run python unit21/genai_code_gate.py --path unit21/genai/sq-app-reviewed. Expected last line:
9 rules: 8 OK, 0 WARN, 1 FAIL
In unit21/genai/sq-app-reviewed/db/schema.cds, change using { managed } to using { cuid, managed }, change entity Quotes : managed { to entity Quotes : cuid, managed { and entity QuoteItems { to entity QuoteItems : cuid {, and delete the two lines that start with key ID.
Replace the IDs in the two CSV files with UUIDs. In calder.quotes-Quotes.csv use 7d3f0c52-1b6e-4a1f-9c2d-000000000001 and ...0002; in calder.quotes-QuoteItems.csv use 5a9e2b71-4c3d-4e8f-8a10-000000000001 and ...0002 for ID, and the matching quote UUIDs for quote_ID.
Run the gate again. Expected last line:
9 rules: 9 OK, 0 WARN, 0 FAIL
Add a line to AGENTS.md: - Use cuid (UUID) keys for new entities. The Fiori MCP server README suggests the same rule for agents.
Run with --report and fill in the decision record in unit21/genai/gate_report.md with option C from the architecture view.
Done when the gate ends with 9 rules: 9 OK, 0 WARN, 0 FAIL and exit code 0 on the reviewed project, AGENTS.md names the new rule, and gate_report.md holds a filled-in decision record. Keep it for the Architect track's capstone pack.
Pick one answer for each question. The explanation appears after you choose.
1In the mental model, where does governance of AI-generated code sit?
Answer: A. Joule, a VS Code assistant with SAP's MCP servers and a coding agent all produce files in a repository. A gate there covers every tool. Production is too late to catch an open service.
2Which parts does SAP's product page list as included in SAP Build Code?
Answer: B. The FAQ on SAP's product page lists SAP Business Application Studio, CAP, SAPUI5, SAP Fiori elements and SAP Mobile Services. Joule Studio and the ABAP tools are separate offerings in the SAP Build family.
Answer: C. A local MCP server runs on the developer's machine with their rights. The README itself recommends pinning so untested updates aren't picked up. G06 asks for an approved package at an exact version.
4Why did the reviewed project move the discount ceiling to srv/lib/discount.js?
Answer: A. The rule is a pure function, so node --test checks it in milliseconds with no server. That also exposed the draft's error: it applied 15% to every channel instead of 5% for direct customers.
5A G04 finding says the sample data has a contactEmail column that the model doesn't have. What should the reviewer suspect first?
Answer: A. Generated sample data should fit the model and be made up. A column the model lacks, holding contacts, hints that someone pasted real data to make it look realistic, which SAP's tutorial says not to do. managed adds only created and modified fields.
6A contractor joins for three months to build a CAP app. Which setup fits Calder's decision?
Answer: A. Calder's option C keeps contractors in dev spaces, so nothing is installed on their machines and access ends with their BTP user. The repository gate applies to everyone; there are no exceptions by employment type.
7Which statement about Joule's licensing in SAP Build Code is accurate as of 27 November 2026?
Answer: C. The feature page says included with Joule Base, the Joule for developers page describes free access under the SAP AI Terms, and the pricing page lists a developer user that includes Joule for developers. Confirm your own terms in writing.
8The gate passes with 8 OK. What should still happen before the pull request merges?
Answer: A. The gate checks what rules can check: roles, secrets, tests, tools, provenance. Whether a 15% ceiling is the right business rule takes a person. Regenerating proves nothing, because output differs each time.
Generative AI-based code development: SAP Build Code (sap.com, read 2026-11-27)— optimized for Java and JavaScript development; turnkey environment for coding, testing, integrations and lifecycle management; FAQ says it includes SAP Business Application Studio, CAP, SAPUI5, SAP Fiori elements and SAP Mobile Services; Joule generates app logic, data models, sample data and test scripts; service center for prebuilt integrations and APIs
SAP Joule for Developers (sap.com, read 2026-11-27)— embedded AI for SAP Build and ABAP; free access for developers using SAP Build and ADT after accepting the SAP AI Terms; enabled by default in SAP Build Code on sign-up; third-party foundation models (OpenAI, PaLM 2, Gemini, Anthropic, Llama, Mistral AI) plus SAP's ABAP model; runtime AI such as SAP AI Core is not part of it
What is SAP Build? (sap.com, read 2026-11-27)— the unified SAP Build offering consolidates application development, automation and low-code UI generation; pro-code with SAP Build Code and the ABAP environments; supports Visual Studio Code and connects to MCP servers; included as part of SAP Business Suite; entitlements in the SAP BTP cockpit
SAP Build pricing (sap.com, Denmark page, read 2026-11-27)— SAP Build base user EUR 3.00, premium user EUR 8.00, developer EUR 40.00 per active user per month, runtime EUR 1.00 per capacity unit; the developer user includes Joule for developers, Joule Studio and low-code and code-first tools; runtime includes Cloud Foundry, ABAP environment, Kyma, CI/CD and cloud transport management; test, demo and development tenants for partners only; 3 to 36 months, automatic renewal
Create a Full-Stack Application with Joule in SAP Build Code (SAP Developers tutorial)— Joule opened from the activity bar in SAP Business Application Studio; slash commands /cap-gen-app, /cap-gen-model, /cap-gen-data, /cap-edit-data, /cap-app-logic; code may differ on each prompt; conversations are sent to SAP-hosted LLMs, so no personal data, credentials or confidential information in messages; verify important details
SAP Empowers AI Developers to Build What Matters (SAP News, 27 October 2026)— SAP TechEd 2026; Joule Studio accessible through Joule Work, no-code and pro-code tools, more than 70 AI models; design-time tooling including AI-assisted development free under fair-use limits; custom agents on the SAP-managed runtime free through December 2026
@sap-ux/fiori-mcp-server README (npm, read 2026-11-27)— MCP server that lets coding assistants create and change SAP Fiori apps; tools such as generate_fiori_app_cap and list_sap_systems; pin a version (example 1.12.2); telemetry on by default with an opt-out; warns against NODE_TLS_REJECT_UNAUTHORIZED=0; suggested AGENTS.md rules including UUID keys