# 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.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/sap-build-code/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 36 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

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](https://www.sap.com/products/technology-platform/developer-tools.html), 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.

### Why it matters to the business

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](https://erpfde.com/topics/cap-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](https://developers.sap.com/tutorials/build-code-test-drive.html)).
- **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](https://developers.sap.com/tutorials/build-code-complex.html)). 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.

### How SAP does it

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](https://www.sap.com/products/technology-platform/developer-tools.html)).
- **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](https://www.sap.com/products/technology-platform/build-code-generation-of-fullstack-applications.html)).
- **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](https://www.sap.com/products/technology-platform/build.html)).
- **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](https://news.sap.com/2025/11/new-agentic-capabilities-sap-btp-supercharge-developers/)). 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](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html) 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](https://www.sap.com/denmark/products/technology-platform/build/pricing.html)). Ask your SAP account team which terms apply to your contract, in writing.

### A policy for AI-generated code on one page

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.

### Questions to ask

- Which of our developers use Joule, and which use other AI assistants? Do we know which tools they connect to SAP systems?
- Which SAP Build terms apply to us: Joule Base, the developer user, or free access under the SAP AI Terms? Until when?
- What may never go into a prompt, and how do developers learn that?
- Where is the review gate: in the pull request, in the pipeline, or both? Who can override it?
- How do we tell generated code from written code six months from now?
- Do our partners' developers follow the same rules in our repositories?
- How will review effort keep up when the amount of code doubles?

### Common misconceptions

- **"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.

### Key terms

- **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.

### Check yourself

1. What is the architect's main question about AI-generated code?
   - A. Which AI assistant the whole team must standardize on this year
   - B. What has to be true before generated code reaches production
   - C. Whether developers should be allowed to use AI at all
   - D. How many lines of code the AI saves each developer per week

   Answer: B. 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.

2. Why does Calder govern the repository instead of picking one AI tool?
   - A. Because SAP Build Code doesn't allow any tools other than Joule
   - B. Because pull requests are the only place SAP lets you see code
   - C. Developers switch tools, and code from any of them arrives there
   - D. Because a repository rule is cheaper than any SAP license

   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.

3. A developer wants realistic sample data and plans to paste a production customer extract into Joule. What should happen?
   - A. Allow it, because Joule runs on SAP-hosted models inside SAP BTP
   - B. Allow it if the extract is deleted from the dev space afterwards
   - C. Allow it for internal customers but not for distributors
   - D. Refuse it: prompts must not hold personal or confidential data

   Answer: D. 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.

4. A generated quote service runs and the demo works. Which risk is still most likely open?
   - A. The app can't be deployed, because generated code is not deployable
   - B. The service names no role, so every signed-in user can use it
   - C. The data model can't be changed after generation by Joule
   - D. The Fiori screens only work inside SAP Business Application Studio

   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.

5. How should a leader treat SAP's pricing for Joule in SAP Build Code as of November 2026?
   - A. As free for everyone, as the Joule for developers page says
   - B. As always included in Joule Base, as the feature page says
   - C. As part of the developer user, as the pricing page lists it
   - D. As unsettled: get the terms for your own contract in writing

   Answer: D. 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.

6. What does a provenance record add that a passing build doesn't?
   - A. Proof that the code was tested on SAP's own systems
   - B. A licence for the generated code from the model provider
   - C. Which files a model made, and which person reviewed each
   - D. A copy of every prompt, so the code can be regenerated exactly

   Answer: C. 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.

## Deep layer

### Mental model

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](https://erpfde.com/topics/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.

### How it works

As described on SAP's pages read on 27 November 2026, a CAP project in SAP Build Code goes through these steps:

1. **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](https://developers.sap.com/tutorials/build-code-test-drive.html)).
2. **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](https://developers.sap.com/tutorials/build-code-complex.html)).
3. **Generate the UI.** The tutorial adds SAP Fiori elements list report pages and previews them.
4. **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](https://www.sap.com/germany/products/technology-platform/continuous-integration-and-delivery.html)). 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](https://community.sap.com/t5/technology-blog-posts-by-sap/announcing-new-sap-build-and-service-catalog-extensions-for-vs-code/ba-p/14261628)). 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](https://unpkg.com/@sap-ux/fiori-mcp-server@latest/README.md)).

```mermaid
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](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html)). 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](https://github.com/sap/mdk-mcp-server)). Treat these servers like any other dependency: approved, pinned and reviewed. [AI supply-chain controls](https://erpfde.com/topics/ai-supply-chain-controls/) shows why.

> **Note** The SAP Build Code documentation on help.sap.com couldn't be opened in this run. The role collections, entitlements and dev space settings for SAP Build Code aren't covered here; check them in SAP's documentation before you design the setup.

### 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.

```mermaid
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]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). The optional test step needs Node.js 22 or later from [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/). This walkthrough doesn't repeat their steps.

> **Note** New words. **CAP** is SAP's Cloud Application Programming Model: you describe data and services in `.cds` files and add JavaScript or Java for logic. A **service** is the API the app offers. **Sample data** is a set of CSV files in `db/data` that CAP loads for testing. A **rule** here is one of Calder's checks, G01 to G08. A **verdict** is OK, WARN (fix soon) or FAIL (breaks a rule). An **exit code** is the number a program returns when it ends: 0 means success, and this script returns 2 when any rule fails, so a pipeline can stop on it. **MCP** (Model Context Protocol) is the standard way an AI assistant calls tools.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account. Everything is free.
- Optional: Node.js 22 or later, to run the reviewed project's unit tests.
- About 30 minutes.

#### Step 1: Open the course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. The `unit21` folder exists from the setup topic. If it doesn't, create it with `mkdir unit21`.

#### Step 2: Create the script

1. In VS Code, create a new file `unit21/genai_code_gate.py`.
2. 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`.

```python
"""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())
```

#### Step 3: Write the draft project and check it

1. Write the draft. It stands in for a first Joule session on Calder's spare-part quote desk:

   ```bash
   python unit21/genai_code_gate.py --init
   ```

   ```text
   Wrote 9 files to unit21/genai/sq-app
   ```

2. Run the gate:

   ```bash
   python unit21/genai_code_gate.py
   ```

3. Expected output:

   ```text
   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
   ```

4. 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.

> **Note** The draft is made up to show the method. It is not output captured from Joule, and Joule won't produce exactly these files; SAP says generated code can differ on every prompt.

#### Step 4: Read why each rule exists

| Finding | What it would cost at Calder |
| --- | --- |
| G01 open service | Any user with a BTP login could read and change every quote. [CAP in depth for architects](https://erpfde.com/topics/cap-for-architects/) shows how roles and row filters work |
| G02 secret in `default-env.json` | A client secret in Git history stays there after you delete the file |
| G03 certificate checks off | Every outbound call from the app trusts any certificate, not just the one self-signed system |
| G04 `contactEmail` column | The model has no such field; the column hints that someone pasted real contacts to make data look realistic |
| G05 inline rule | Calder's ceiling is 15% for distributors and 5% for direct customers; the draft applies 15% to everyone, and nothing tests it |
| G06 `@latest` and an unknown server | Tomorrow's version, or a stranger's package, runs on the developer's machine with their rights |
| G07 no provenance | Six months on, nobody can say which code a person wrote |

#### Step 5: Check the reviewed project

1. Write the version after a developer worked through the findings:

   ```bash
   python unit21/genai_code_gate.py --reviewed
   ```

   ```text
   Wrote 12 files to unit21/genai/sq-app-reviewed
   ```

2. Check it, and write a report:

   ```bash
   python unit21/genai_code_gate.py --path unit21/genai/sq-app-reviewed --report
   ```

3. Expected output:

   ```text
   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
   ```

4. 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.

> **Note** Version `1.12.2` of the Fiori MCP server is the example the server's own README uses for pinning, taken as the approved version in this course. Pin the version your team has actually tested.

#### 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.

1. Go into the reviewed project:

   - **Windows (PowerShell):**

     ```powershell
     cd unit21\genai\sq-app-reviewed
     ```

   - **macOS / Linux:**

     ```bash
     cd unit21/genai/sq-app-reviewed
     ```

2. Run Node's built-in test runner:

   ```bash
   node --test
   ```

3. The last lines should include:

   ```text
   # tests 4
   # pass 4
   # fail 0
   ```

4. 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:

```bash
python unit21/genai_code_gate.py --path path/to/your-project
```

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.

#### Step 8: Save your work

```bash
git add unit21/genai_code_gate.py unit21/genai
git commit -m "Unit 21: review gate for AI-generated CAP code"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `DRAFT_FILES`, `REVIEWED_FILES` | 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](https://erpfde.com/topics/cap-for-architects/) does.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `Python was not found` | Python isn't on your path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `unit21/genai/sq-app not found` | You skipped `--init` | Run `python unit21/genai_code_gate.py --init` |
| Output differs from the expected text | You edited the sample files | Delete the `unit21/genai` folder and run `--init` and `--reviewed` again |
| `json.decoder.JSONDecodeError` | Your own project's `.mcp.json` isn't valid JSON | Fix the file; the gate needs to read it |
| `node: command not found` | Node.js isn't installed | Step 6 is optional; install Node.js from Set up for Unit 5 |
| `node --test` finds no tests | You ran it from the wrong folder, or Node.js is older than 22 | Run it inside `sq-app-reviewed`; check `node --version` |
| Nothing about the network | The script never goes online | No key, proxy or account is involved |

### The SAP way

As read on SAP's pages on 27 November 2026:

- **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](https://www.sap.com/products/technology-platform/developer-tools.html)).
- **What Joule generates in it.** Data models, services, sample data and UI annotations from natural language; application logic; unit tests ([feature page](https://www.sap.com/products/technology-platform/build-code-generation-of-fullstack-applications.html)). 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](https://developers.sap.com/tutorials/build-code-complex.html)).
- **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](https://blogs.sap.com/t5/technology-blogs-by-sap/upgrade-sap-business-application-studio-to-sap-build-code/ba-p/13661500)).
- **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](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html): 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](https://www.sap.com/denmark/products/technology-platform/build/pricing.html) (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](https://www.sap.com/products/technology-platform/build.html) 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](https://news.sap.com/2025/11/new-agentic-capabilities-sap-btp-supercharge-developers/)). The CAP MCP server is covered in [Coding agents for SAP developers](https://erpfde.com/topics/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](https://news.sap.com/2026/10/sap-teched-ai-developers-build-what-matters-autonomous-execution/)). Joule Studio builds agents and Joule skills; SAP Build Code builds applications. [Joule and Joule Studio](https://erpfde.com/topics/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](https://www.sap.com/germany/products/technology-platform/continuous-integration-and-delivery.html)). A gate like the one above runs as an extra step in whatever pipeline you use.

> **Note** None of the pages read today give a general-availability or end date for the VS Code extensions or the MCP servers for SAP Build. The Fiori MCP server is published on npm with versioned releases; check each tool's own page for its status before you approve it.

### Build vs. SAP

| Situation | Use | Why |
| --- | --- | --- |
| New CAP or Fiori app, team new to CAP | SAP Build Code with Joule | Templates, generators and the service center in one place; generated code teaches the patterns |
| Team already works in VS Code with its own assistant | SAP's VS Code extensions and MCP servers, approved and pinned | Same generators, the team's own editor; fewer tools to retrain on |
| Contractors or partners on short assignments | Business Application Studio dev spaces | Nothing installed on their machines; access ends with their BTP user |
| ABAP Cloud extensions | ADT with Joule for developers, ABAP AI capabilities | Covered in [Coding agents for SAP developers](https://erpfde.com/topics/coding-agents-for-sap-developers/) |
| Agents and Joule skills | Joule Studio | A different product for a different output |
| Any of the above | One repository gate and one pipeline | Governance shouldn't depend on the editor |

### Architecture view

**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](https://erpfde.com/topics/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](https://erpfde.com/topics/btp-connectivity/), and their roles come from [the BTP security model](https://erpfde.com/topics/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.

**The decision to record** (short ADR form from [the design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **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.**

1. Where do prompts go for each assistant in use, and what may never be in them?
2. What stops a generated service without roles from reaching production?
3. Who approves an MCP server, and how is its version fixed?
4. How do we tell generated code from written code, and who reviewed it?
5. What happens to review capacity when generation doubles the code volume?

### Production concerns

- **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](https://erpfde.com/topics/fit-to-standard-and-extension-choices/).

### Where AI fits

- **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](https://erpfde.com/topics/coding-agents-for-sap-developers/).
- **A new risk.** Tool servers and model routes are new parts of the software supply chain, and tool outputs can carry prompt injection. See [AI supply-chain controls](https://erpfde.com/topics/ai-supply-chain-controls/) and [Prompt injection and tool poisoning](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/).
- **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](https://erpfde.com/topics/intent-based-development-with-joule-studio/).

### Pitfalls

- **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.

### Exercise

Add a ninth rule to the gate, fix the reviewed project so it passes, and keep the report for the capstone pack.

1. Open `unit21/genai_code_gate.py`.
2. 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):

   ```python
       # 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")
   ```

3. Run `python unit21/genai_code_gate.py --path unit21/genai/sq-app-reviewed`. Expected last line:

   ```text
   9 rules: 8 OK, 0 WARN, 1 FAIL
   ```

4. 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`.
5. 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`.
6. Run the gate again. Expected last line:

   ```text
   9 rules: 9 OK, 0 WARN, 0 FAIL
   ```

7. Add a line to `AGENTS.md`: `- Use cuid (UUID) keys for new entities.` The Fiori MCP server README suggests the same rule for agents.
8. 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.

### Check yourself

1. In the mental model, where does governance of AI-generated code sit?
   - A. In SAP Business Application Studio, because Joule runs there
   - B. In the model provider's settings, because prompts go there
   - C. At the repository, where code from every tool arrives
   - D. In the production subaccount, where the app finally runs

   Answer: C. 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.

2. Which parts does SAP's product page list as included in SAP Build Code?
   - A. ABAP Development Tools, Joule Studio, SAP Signavio and SAP LeanIX
   - B. Business Application Studio, CAP, SAPUI5, Fiori elements, Mobile Services
   - C. Integration Suite, Cloud Connector, SAP HANA Cloud and Datasphere
   - D. SAP Build Apps, Build Process Automation, Work Zone and Joule Studio

   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.

3. The draft project's `.mcp.json` runs `@sap-ux/fiori-mcp-server@latest`. Why does G06 fail it?
   - A. SAP doesn't allow the Fiori MCP server outside Business Application Studio
   - B. The Fiori MCP server needs a paid SAP Build developer licence to run
   - C. `@latest` downloads the server from a source other than npm
   - D. Any future version would run without anyone testing or approving it

   Answer: D. 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.

4. Why did the reviewed project move the discount ceiling to `srv/lib/discount.js`?
   - A. CAP refuses to load handlers that contain numbers
   - B. A plain function can be tested without starting the CAP server
   - C. Joule can only regenerate files that sit under `srv/lib`
   - D. The Fiori MCP server reads business rules from that folder

   Answer: B. 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.

5. A G04 finding says the sample data has a `contactEmail` column that the model doesn't have. What should the reviewer suspect first?
   - A. That CAP added the column automatically from the `managed` aspect
   - B. That the column comes from the Fiori elements UI annotations
   - C. That real contact data may have gone into a prompt or the data
   - D. That the CSV separator is wrong and two columns were merged

   Answer: C. 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.

6. A contractor joins for three months to build a CAP app. Which setup fits Calder's decision?
   - A. Their own laptop with any assistant, since the gate catches problems
   - B. A dev space in Business Application Studio, with the same gate in the pipeline
   - C. Direct access to the production subaccount to save deployment time
   - D. An exception from the gate, because contractors work under contract terms

   Answer: B. 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.

7. Which statement about Joule's licensing in SAP Build Code is accurate as of 27 November 2026?
   - A. SAP has confirmed it is free for all customers until the end of 2027
   - B. SAP has confirmed it needs AI Units consumed per generated file
   - C. SAP's pages describe Joule Base, free access and a paid developer user
   - D. SAP has withdrawn Joule from SAP Build Code in favour of Joule Studio

   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.

8. The gate passes with 8 OK. What should still happen before the pull request merges?
   - A. Nothing: a passing gate means the generated code is correct
   - B. Regenerate the code once more to confirm the model gives the same result
   - C. Deploy straight to production, since the pipeline will catch the rest
   - D. A person reviews the logic, because rules can't judge business meaning

   Answer: D. 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.

## Sources

- [Generative AI-based code development: SAP Build Code (sap.com, read 2026-11-27)](https://www.sap.com/products/technology-platform/developer-tools.html): 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 Build Code, generation of full-stack applications (sap.com AI feature page, read 2026-11-27)](https://www.sap.com/products/technology-platform/build-code-generation-of-fullstack-applications.html): Joule generates data models, services, sample data and UI annotations from natural language, creates application logic and unit tests; included with Joule Base at no additional cost, a Joule Base subscription is required; contract duration on request
- [SAP Joule for Developers (sap.com, read 2026-11-27)](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html): 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)](https://www.sap.com/products/technology-platform/build.html): 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)](https://www.sap.com/denmark/products/technology-platform/build/pricing.html): 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)](https://developers.sap.com/tutorials/build-code-complex.html): 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
- [Create a Full-Stack Application with SAP Fiori UI using Joule in SAP Build Code (SAP Developers tutorial, updated 2024-11-10)](https://developers.sap.com/tutorials/build-code-test-drive.html): assumes an SAP BTP trial account; starts in the SAP Build lobby (Create, Build an Application, SAP Build Code, Full-Stack Application); Joule generates the CAP data model and service, sample data, logic and Fiori elements apps
- [SAP Empowers AI Developers to Build What Matters (SAP News, 27 October 2026)](https://news.sap.com/2026/10/sap-teched-ai-developers-build-what-matters-autonomous-execution/): 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
- [New Agentic Capabilities on SAP BTP Supercharge Developers (SAP News, 5 November 2025)](https://news.sap.com/2025/11/new-agentic-capabilities-sap-btp-supercharge-developers/): local MCP servers for SAP Build for code assistants such as Cursor, Windsurf, Claude Code, Cline and OpenAI Codex; SAP Build extension pack for VS Code available; extensions to be published on the Open VSX Registry
- [Announcing new SAP Build and Service Catalog extensions for VS Code (SAP Community, SAP employee, November 2025)](https://community.sap.com/t5/technology-blog-posts-by-sap/announcing-new-sap-build-and-service-catalog-extensions-for-vs-code/ba-p/14261628): SAP Build Full-Stack Extension Pack bundles the full-stack tools; Service Catalog extension is the local version of the service center, starting with the ABAP catalog and on-premise systems with basic authentication; Open VSX release planned; post date not shown in the page text
- [@sap-ux/fiori-mcp-server README (npm, read 2026-11-27)](https://unpkg.com/@sap-ux/fiori-mcp-server@latest/README.md): 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
- [SAP Continuous Integration and Delivery (sap.com, read 2026-11-27)](https://www.sap.com/germany/products/technology-platform/continuous-integration-and-delivery.html): predefined CI/CD pipelines that test, build and deploy; connect a Git repository and optional webhooks; upload the artifact to SAP Cloud Transport Management; billed in compute hours
- [Upgrade SAP Business Application Studio to SAP Build Code (SAP Community, SAP employee)](https://blogs.sap.com/t5/technology-blogs-by-sap/upgrade-sap-business-application-studio-to-sap-build-code/ba-p/13661500): a Business Application Studio standard-plan subscription is updated to the build-code plan in Instances and Subscriptions; then the SAP Build lobby opens; earlier projects stay reachable through the Dev Space Manager
