# How Joule works: the request path an architect can defend

> Follow one Joule request from sign-in to answer or action, see which component decides what, and review a Joule design for identity, scope and logging.

- Course: Orchestrate, Unit 23 · Joule and the AI platform: the architect's view
- Page: https://erpfde.com/topics/how-joule-works/
- Updated: 2026-11-28
- Reading time: Foundational 8 min, Deep 35 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

When someone types a question into Joule, a chain of SAP components handles it. One proves who the person is. One works out what this person is allowed to ask Joule for. A catalog picks the skill that fits the question. A language model reads the question and either answers it from documents or asks for a business function to be run. That function then calls the SAP system **as that person**, and the SAP system applies its usual authorizations before anything comes back.

So Joule is not one box. It is a request path through identity, a catalog, a model and your back-end systems. Each part makes one decision, and an architect needs to know which part makes which.

The decision for you: approve a Joule design only when its diagram shows, for each kind of request, where the user's identity travels and which system says yes or no.

### Why it matters to the business

Take Calder Pumpworks, the course's fictional pump maker. Its customer service clerks want to ask Joule "show me order 1000002" and "how many orders are blocked for credit?". Its credit analyst wants to release a credit block from the same chat.

Three things can go wrong, and each sits in a different part of the path:

| What goes wrong | Where it is decided | Business effect |
| --- | --- | --- |
| A sales rep sees a distributor order they may not see in SAP | How Joule calls SAP: as the person, or as one shared technical user | Data leak; audit finding |
| A clerk releases a credit block they are not allowed to release | Which functions the person's roles offer, and SAP's own check | Credit risk; a control fails |
| HR questions work, but S/4HANA questions don't, for the same person | Identity: two identity tenants make two separate Joules | Split experience; double setup cost |

None of these are model problems. They are design decisions made in identity, roles and connections, which is why the architecture matters more than the prompt.

There is also a cost angle. Identity and Work Zone setup is shared by every product Joule serves. Getting it right once makes the second and third product cheap to add; getting it wrong means rebuilding it per product.

### How SAP does it

As of 28 November 2026, SAP's own pages describe the path in these pieces:

- **Joule is an SAP-run service on BTP.** SAP's [2025 feature scope description](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/9c3432ecab90406e99dbc987389334ed.pdf) calls it a multitenant SaaS on SAP BTP running on Amazon Web Services. Customers set it up; SAP runs it.
- **One Joule per landscape tier.** SAP Learning's [unified instance lesson](https://learning.sap.com/courses/setting-up-joule-across-your-organizational-system-landscapes/setting-up-a-unified-joule-instance) says every application in one Joule must use the same SAP Cloud Identity Services tenant, with one tenant for production and one for non-production. Different tenants mean separate Joule instances.
- **Four kinds of request.** SAP's [reference architecture](https://architecture.learning.sap.com/docs/ref-arch/464deb) (updated 16 March 2026) names informational, navigational, transactional and analytical patterns, and describes a five-step flow from the Joule client to a filtered answer.
- **The model.** The same page says the dialog model comes from partner models offered through SAP's AI foundation and the generative AI hub, and that partner contracts prohibit training on customer data.
- **Identity to the back end.** SAP's [Joule identity architecture](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f) has Joule call business functions through the BTP Destination service with **principal propagation**: the user's token is exchanged for one the target system accepts, so SAP checks that user's own authorizations.
- **The newer layer.** SAP Learning's [Joule architecture lesson](https://learning.sap.com/courses/introducing-joule/understanding-joule-s-architecture_a1ea765b-6dc7-4cd9-b741-2a45d9eb9b3a) describes Joule Work with an **Agent Gateway** that "every request from Joule to an agent or backend service passes through", handling authentication, principal propagation and tool discovery. It gives no release status, so ask which path applies to your tenant.
- **Records.** The [2026 feature scope description](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/Joule_FSD.pdf) (version 3.0.0, 5 May 2026) says conversation history, analytics and feedback are captured for auditability, and that users can ask for their conversation data to be retrieved or deleted.

> **Note** **For functional consultants:** Joule never replaces the authorization concept you designed. A Joule function shows or changes only what the user's SAP roles allow, so a Joule test case is the same request run by two users with different roles. What is new is a second layer: which Joule functions a role offers at all. Ask to see that mapping beside your role matrix, and test both layers.

### One request, five decisions

Every Joule request passes the same five decisions. Use this table when you read a design or a vendor slide.

| Decision | Made by | What it uses | If it's wrong |
| --- | --- | --- | --- |
| Who is asking? | SAP Cloud Identity Services | The company sign-in, one tenant per tier | The user isn't known, or lands in a second Joule |
| What may this person ask Joule for? | Joule with SAP Build Work Zone | The person's role assignments and the content each role carries | Functions offered to people who shouldn't see them |
| Which skill fits? | Joule's catalog of scenarios and knowledge | The question, the current app, the user's context | Wrong skill picked; test with real questions |
| Answer, or run a function? | The dialog model | The question plus grounding documents or function results | A fluent but wrong answer; ground it and cite sources |
| May this person see or change this record? | The SAP back-end system | The person's own SAP authorizations, reached by principal propagation | A shared technical user sees everything |

The first two and the last are where architects earn their fee. The middle two are where testing earns its fee.

### Questions to ask

Ask your team, partner or SAP account team:

- Draw one request of each kind (informational, navigational, transactional, analytical) on our landscape. Where does the user's identity travel at each hop?
- Do all products in this Joule use the same identity tenant, and is it the production one?
- Does every back-end call run as the signed-in user, or does any destination use a shared technical user?
- Which roles offer which Joule functions, and who keeps that list in line with our SAP role matrix?
- Do all transactional functions ask the user to confirm before they change data?
- Which data centers will process our conversations and document grounding, and how long is conversation history kept?
- Who answers a user's request to export or delete their conversation data?
- Does our tenant use the Agent Gateway path or destinations for back-end calls today, and when does that change?

### Common misconceptions

- **"Joule is a chatbot that reads our database."** Joule calls published functions and APIs of each SAP system, and that system applies its own authorizations.
- **"If the model is safe, Joule is safe."** Most of the risk sits in identity, role content and connections, which are configured by your team.
- **"A technical user is simpler and works the same."** It works, but every user then sees what the technical user sees, and SAP's logs show one name for everyone.
- **"Hiding a function in Joule is the security control."** It is a convenience. The SAP system's own check is the control; design both, rely on the second.
- **"Every SAP product gets its own Joule."** SAP's guidance is one Joule per tier, shared across products, on one identity tenant.
- **"Joule's model learns from our data."** SAP's reference architecture says partner contracts prohibit training on customer data.

### Key terms

- **Joule client:** the chat panel embedded in an SAP application, Work Zone or the mobile app.
- **SAP Cloud Identity Services:** SAP's identity service; Identity Authentication signs users in, Identity Provisioning copies users and roles between systems.
- **Joule function:** a business action Joule can run, such as reading an order or releasing a block.
- **Role content:** the mapping from a role to the Joule functions and apps it offers, resolved through SAP Build Work Zone.
- **Dialog model:** the language model that reads the question and decides to answer or call a function.
- **Grounding:** giving the model documents or data so its answer rests on your facts.
- **Principal propagation:** passing the signed-in user's identity to the back end, so it applies that user's authorizations.
- **Destination:** a BTP configuration that says how to reach a system and how to authenticate.

### Check yourself

1. A partner's Joule slide shows one box labeled "Joule" between users and S/4HANA. What is missing for an architecture review?
   - A. The name of the language model and its parameter count
   - B. Where identity travels and who decides at each hop
   - C. The number of skills SAP ships for S/4HANA this year
   - D. The color scheme of the Joule panel in each application

   Answer: B. Joule is a request path through identity, role content, a catalog, a model and the back end. A reviewer needs to see where the user's identity goes and which component decides, because that is where leaks and control failures come from.

2. A sales rep sees a distributor order in Joule that SAP would not show them. What is the most likely cause?
   - A. The dialog model was trained on the distributor's orders
   - B. The rep's question used the wrong words for the order
   - C. Joule reaches SAP through a shared technical user
   - D. Work Zone shows the order to every user by default

   Answer: C. When a destination logs on as a technical user, SAP checks that user's authorizations instead of the rep's. Principal propagation passes the rep's own identity, so SAP refuses what the rep may not see.

3. HR questions work in Joule, but S/4HANA questions fail for the same employee. Which design choice fits that symptom?
   - A. The two products sit on different identity tenants
   - B. The S/4HANA system has too many open sales orders
   - C. The employee asked in German instead of in English
   - D. Joule has no informational pattern for S/4HANA data

   Answer: A. SAP's unified setup needs every product in one Joule to share one identity tenant. Different tenants mean separate Joule instances, so one person ends up with two assistants that know different things.

4. Your CISO asks what stops a clerk from releasing a credit block through Joule. What is the accurate answer?
   - A. The clerk's prompt is checked by the model for bad intent
   - B. Joule hides the function, which is the control on its own
   - C. The confirmation step blocks anyone who is not a manager
   - D. SAP checks the clerk's own authorization on arrival

   Answer: D. Hiding a function in role content is a convenience and confirmation stops accidents. The control is the SAP system's own authorization check, which works only if the call carries the clerk's identity.

5. What should you ask before signing off conversation logging for a Joule rollout?
   - A. Whether Joule can answer questions about the weather
   - B. Where chats are processed; who owns deletion requests
   - C. Whether the model vendor publishes its training cost
   - D. How many pages SAP's feature scope description has

   Answer: B. SAP's feature scope description says conversation history is captured and users can ask for their data to be retrieved or deleted. Someone must own those requests, and the processing location is a data protection question your team has to answer.

6. Why is identity design worth getting right before the first Joule pilot?
   - A. Because SAP charges per identity tenant every month
   - B. Because the model needs identity data for training
   - C. Because later products reuse the same identity setup
   - D. Because pilots run without any authorization checks

   Answer: C. One identity tenant per tier and consistent role content are shared by every product Joule serves. Done once, they make later products cheap to add; done wrong, they are rebuilt per product.

## Deep layer

### Mental model

A Joule request is a **relay of decisions**, and each runner holds a different baton:

1. **Identity** answers "who is this?" and hands on a token.
2. **Role content** answers "what may they ask for?" and hands on a list of functions.
3. **The catalog** answers "which function or document fits?" and hands on a candidate.
4. **The dialog model** answers "answer, or call?" and hands on a function call or a grounded reply.
5. **The back end** answers "may this user see or change this record?" and hands back data or a refusal.

The model sits in the middle, and it is the only runner that guesses. Everything around it is deterministic configuration your team owns. A defensible design keeps the guess away from the decisions that need certainty: the model may pick the wrong function, but it can only pick from the user's list, and whatever it picks still runs as the user against SAP's own checks.

[Joule and Joule Studio](https://erpfde.com/topics/joule-and-joule-studio/) taught the builder's version of this (a router in front of a catalog). This topic adds what an architect has to prove: where the identity goes, and which system decides.

### How it works

#### The request path as SAP documents it

The sequence below combines two SAP Architecture Center pages: the five-step flow in [Integrating and Extending Joule](https://architecture.learning.sap.com/docs/ref-arch/464deb) (updated 16 March 2026) and the runtime identity flow in [Identity and Access Management for SAP Joule](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f) (updated 22 September 2025). The Cloud Connector hop comes from SAP's [Private Edition page](https://architecture.learning.sap.com/docs/ref-arch/ebe268) and applies when the back end is S/4HANA Cloud Private Edition.

```mermaid
sequenceDiagram
  participant U as User
  participant C as Joule client
  participant IAS as Identity Authentication
  participant J as Joule
  participant WZ as Work Zone navigation
  participant M as Dialog model
  participant D as Destination service
  participant CC as Cloud Connector
  participant S as S/4HANA
  U->>C: question
  C->>IAS: sign in (federated to company IdP)
  IAS-->>C: OIDC token
  C->>J: question + token
  J->>WZ: user, roles, role content
  WZ-->>J: functions this user may use
  J->>J: scenario catalog, knowledge catalog, user context
  J->>M: enriched prompt
  M-->>J: grounded answer, or call function F
  J->>D: call F with user token
  D->>IAS: exchange token for target system
  D->>CC: request as the user
  CC->>S: OData call
  S-->>J: data or refusal (user's authorizations)
  J-->>C: filtered reply
```

Step by step, with the source for each:

1. **Sign-in.** With no session, Joule sends the user to Identity Authentication, which can federate to the company's own identity provider and returns an OIDC access token ([IAM page](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f)).
2. **Functions for this user.** Joule asks the Work Zone navigation service to combine the user, their role assignments and the **Common Data Model** content that maps each item (such as a Joule function) to a role. The result is the set of functions this user can use in this session ([IAM page](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f)). Role assignments get there by Identity Provisioning, which syncs users and roles over SCIM.
3. **Context.** Joule checks the **Scenario Catalog** (metadata for scenarios, functions and skills), the **Knowledge Catalog** (SAP and customer knowledge for retrieval), and user context: the current app, licensed apps, roles and chat history ([reference architecture](https://architecture.learning.sap.com/docs/ref-arch/464deb)).
4. **The model.** Joule sends an enriched prompt to the dialog-management model, which the same page says comes from partner models available through SAP's AI foundation and the generative AI hub. The model returns a grounded answer or asks Joule to call a function.
5. **The call.** Joule calls the function through the Destination service with principal propagation: the Destination service exchanges Joule's user token at Identity Authentication for a token the target application accepts ([IAM page](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f)). For Private Edition the call goes through the Cloud Connector, and the OData services behind transactional tasks must be activated in the back end ([Private Edition page](https://architecture.learning.sap.com/docs/ref-arch/ebe268)).
6. **The reply.** The back end answers based on the user's access; Joule filters the response and returns it ([reference architecture](https://architecture.learning.sap.com/docs/ref-arch/464deb)).

> **Note** **New words.** An **OIDC token** is a signed, short-lived proof of who the user is, issued after sign-in (OpenID Connect is the standard). **SCIM** is a standard API for copying users and groups between systems. **OData** is the REST protocol most SAP business APIs use. **Federation** means Identity Authentication trusts the company's own sign-in (such as Microsoft Entra ID) instead of keeping its own passwords.

#### The four request patterns

SAP's [reference architecture](https://architecture.learning.sap.com/docs/ref-arch/464deb) names four patterns. They take different routes through the path above:

| Pattern | Example at Calder | Route | Reaches the back end? |
| --- | --- | --- | --- |
| Informational | "What does our credit policy say about distributors?" | Knowledge Catalog and document grounding | No, unless the answer needs data |
| Navigational | "Take me to the app for blocked orders" | Role content gives the app; Joule returns a link | No |
| Transactional | "Release the credit block on order 1000002" | Function call with confirmation, then the back end | Yes, and it changes data |
| Analytical | "How many orders are blocked for credit?" | Function call, then the model writes the answer | Yes, read only |

The 2026 [feature scope description](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/Joule_FSD.pdf) names Microsoft SharePoint, Google Drive and SAP Build Work Zone as document grounding sources, with DOCX, PDF, PPTX and HTML files. The 2025 version says that when no intent fits, Joule falls back to searching SAP Help Portal content.

#### Two descriptions of the back-end hop

SAP documents the hop from Joule to back-end systems in two ways, and both are in circulation in November 2026:

| | Destinations with principal propagation | Agent Gateway |
| --- | --- | --- |
| Described in | [IAM reference architecture](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f) (September 2025), [Private Edition page](https://architecture.learning.sap.com/docs/ref-arch/ebe268), [Joule Studio Classic page](https://architecture.learning.sap.com/docs/ref-arch/ff07b1) (October 2026) | SAP Learning's [Joule architecture lesson](https://learning.sap.com/courses/introducing-joule/understanding-joule-s-architecture_a1ea765b-6dc7-4cd9-b741-2a45d9eb9b3a) for Joule Work |
| What carries identity | The Destination service exchanges the user token at Identity Authentication | The gateway handles authentication and principal propagation |
| Also does | Connectivity through the Cloud Connector for private systems | Tool discovery; sits beside AI Agent Hub and Task Center |
| Status stated | Documented reference architecture | No release status on the lesson |

The principle is the same in both: the back end sees the signed-in user. What changes is which component you configure and monitor. [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/) covers the Agent Gateway's inbound A2A route for outside agents, which SAP announced as generally available in October 2026.

#### What gets recorded

The 2026 feature scope description says Joule captures conversation history, analytics and feedback for auditability; users can search their conversations, ask for retrieval or deletion of personal data, and download diagnostic traces; administrators get usage analytics by product, scenario and client type. It states no retention periods and no regions. The 2025 version points to a separate "Data Centers Supported by Joule" page for regions, which this run could not open. Treat retention and processing location as questions to settle with SAP in writing.

Logging in the back end is your own: with principal propagation, the S/4HANA change log shows the real user. With a technical user, it shows the technical user for everyone.

### Build it yourself

**Before you start:** finish [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 23](https://erpfde.com/topics/set-up-for-unit-23/). This lab needs no SAP account, no key and no network: Joule has no public trial, so you trace the path on a stand-in of Calder's design.

You will write Calder's Joule design as a file, review it against ten rules, trace six requests through it hop by hop, compare a partner's draft that fails, and produce a sequence diagram you can paste into a design document.

```mermaid
flowchart LR
  I[--init] --> DR[joule_flow_draft.json]
  I --> RV[joule_flow_reviewed.json]
  DR --> R[--review<br/>rules F01-F10]
  RV --> R
  RV --> T[--trace<br/>R01-R06]
  DR --> T
  T --> L[joule_trace.jsonl]
  RV --> MM[--mermaid R03]
  MM --> D[joule_R03.mmd]
```

The script is a **course stand-in**. Its scenario matching counts keywords and its "dialog model" is a rule, so it says nothing about how SAP's model chooses. What it does model faithfully is the order of decisions SAP documents and where each one can go wrong.

> **Note** **New words.** **JSON** is a text format for structured data. A **trace** is a step-by-step record of one request. An **exit code** is the number a program returns when it ends: 0 means fine, 2 here means the review found a FAIL. **Mermaid** is a text format for diagrams that many tools, including this site and GitHub, draw for you.

#### What you need

- The course folder `orchestrate-course` with its `.venv`.
- No account, no key, no cost. The script uses only Python's built-in modules, so `requirements.txt` doesn't change.
- Time: about 35 minutes.

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

1. Open VS Code, then **File > Open Folder** and choose `orchestrate-course`.
2. Open a terminal with **Terminal > New Terminal**.
3. Turn on the virtual environment:
   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. Make the `unit23` folder if it doesn't exist yet:
   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit23
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit23
     ```

You should see `(.venv)` at the start of the prompt.

#### Step 2: Create the script

1. In VS Code, create the file `unit23/joule_flow.py`.
2. Paste the code below and save.

```python
"""Trace a Joule request through Calder's design, and review the design.

Usage (run from the orchestrate-course folder):
  python unit23/joule_flow.py --init                      write the draft and reviewed designs
  python unit23/joule_flow.py --design FILE --review      check the design against rules F01-F10
  python unit23/joule_flow.py --design FILE --trace       run every request in the design, hop by hop
  python unit23/joule_flow.py --design FILE --trace --only R03
  python unit23/joule_flow.py --design FILE --mermaid R03 write unit23/joule_R03.mmd (a sequence diagram)

Options:
  --force   let --init overwrite existing design files

Built-in modules only, no account, no network, no randomness. This is a course stand-in:
the scenario matching and the "dialog model" are simple keyword rules, not SAP's logic.
Calder Pumpworks is fictional; users, roles, functions, rules F01-F10 and records are
course labels, not SAP values.
"""
import argparse
import copy
import json
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent

REVIEWED = {
    "as_of": "2026-11-28",
    "joule_instance": {
        "name": "joule-prod", "tier": "production", "subaccount": "calder-ai-prod",
        "identity_tenant": "calder-ias", "work_zone": "standard",
    },
    "identity": {"global_user_id": "user_uuid", "role_sync": "Identity Provisioning from S4P"},
    "products": [
        {"id": "S4P", "name": "SAP S/4HANA Cloud Private Edition (CP10)", "tier": "production",
         "identity_tenant": "calder-ias",
         "destination": {"name": "S4_ODATA", "proxy": "OnPremise", "location_id": "RK",
                         "authentication": "PrincipalPropagation",
                         "cloud_connector": "SCC-RK-P", "virtual_host": "s4p-api:443"}},
        {"id": "SF-EC", "name": "SAP SuccessFactors Employee Central", "tier": "production",
         "identity_tenant": "calder-ias", "destination": None},
    ],
    "documents": [
        {"id": "DOC-CREDIT-01", "title": "Calder credit policy for distributors",
         "repository": "SharePoint", "owner": "00100304",
         "keywords": ["credit", "policy", "distributor"],
         "text": "Distributor orders above the credit limit stay blocked until the credit analyst "
                 "releases them; the analyst records a reason."},
    ],
    "functions": {
        "search_documents": {"kind": "informational", "keywords": ["policy", "says"]},
        "open_blocked_orders_app": {"kind": "navigational", "keywords": ["take", "app"],
                                    "target": "Sales orders with blocks (course link)"},
        "count_blocked_orders": {"kind": "analytical", "keywords": ["how", "many", "blocked"],
                                 "product": "S4P", "object": "sales_orders", "auth_field": "sales_channels"},
        "get_sales_order": {"kind": "informational", "keywords": ["show", "order"],
                            "product": "S4P", "object": "sales_orders", "auth_field": "sales_channels"},
        "release_credit_block": {"kind": "transactional", "keywords": ["release", "credit", "block"],
                                 "product": "S4P", "object": "sales_orders", "auth_field": "sales_channels",
                                 "auth_flag": "credit_release", "confirm": True},
    },
    "roles": {
        "JOULE_O2C_CLERK": ["search_documents", "open_blocked_orders_app",
                            "count_blocked_orders", "get_sales_order"],
        "JOULE_CREDIT_ANALYST": ["release_credit_block"],
    },
    "users": {
        "00100265": {"label": "customer service clerk", "identity_tenant": "calder-ias",
                     "roles": ["JOULE_O2C_CLERK"],
                     "sap_auth": {"sales_channels": ["10", "20", "30"], "credit_release": False}},
        "00100266": {"label": "inside sales rep", "identity_tenant": "calder-ias",
                     "roles": ["JOULE_O2C_CLERK"],
                     "sap_auth": {"sales_channels": ["10"], "credit_release": False}},
        "00100304": {"label": "credit analyst", "identity_tenant": "calder-ias",
                     "roles": ["JOULE_O2C_CLERK", "JOULE_CREDIT_ANALYST"],
                     "sap_auth": {"sales_channels": ["10", "20", "30"], "credit_release": True}},
    },
    "records": {
        "sales_orders": [
            {"id": "1000002", "partner": "Hallam Fluid Systems", "channel": "20", "problem": "credit block"},
            {"id": "1000003", "partner": "Brennock Water Utility", "channel": "10", "problem": "payment terms missing"},
            {"id": "1000006", "partner": "Brennock Water Utility", "channel": "10", "problem": "billing block AC"},
            {"id": "1000007", "partner": "Brennock Water Utility", "channel": "10", "problem": "delivery block HC"},
        ],
    },
    "technical_user": None,
    "privacy_contact": "00100292",
    "requests": [
        {"id": "R01", "user": "00100265", "text": "What does our credit policy say about distributors?", "expect": "ANSWERED"},
        {"id": "R02", "user": "00100265", "text": "Take me to the app for blocked orders", "expect": "NAVIGATED"},
        {"id": "R03", "user": "00100266", "text": "Show me order 1000002", "expect": "REFUSED"},
        {"id": "R04", "user": "00100265", "text": "How many orders are blocked for credit?", "expect": "ANSWERED"},
        {"id": "R05", "user": "00100304", "text": "Release the credit block on order 1000002", "expect": "CHANGED"},
        {"id": "R06", "user": "00100265", "text": "Release the credit block on order 1000002", "expect": "NOT OFFERED"},
    ],
}


def make_draft():
    d = copy.deepcopy(REVIEWED)
    d["products"][1]["identity_tenant"] = "calder-ias-hr"
    d["products"].append({"id": "S4Q", "name": "SAP S/4HANA Cloud Private Edition (quality)",
                          "tier": "non-production", "identity_tenant": "calder-ias-test", "destination": None})
    d["products"][0]["destination"]["authentication"] = "BasicAuthentication"
    d["technical_user"] = "TU_JOULE"
    d["functions"]["release_credit_block"]["confirm"] = False
    d["roles"]["JOULE_O2C_CLERK"].append("release_credit_block")
    d["documents"][0]["owner"] = None
    d["privacy_contact"] = None
    return d


# ---------------------------------------------------------------- review

def review(d):
    out = []

    def add(rule, verdict, text):
        out.append((rule, verdict, text))

    ji = d["joule_instance"]
    wrong = [p["id"] for p in d["products"] if p["identity_tenant"] != ji["identity_tenant"]]
    add("F01", "FAIL" if wrong else "OK",
        f"products on another identity tenant (a separate Joule instance): {', '.join(wrong)}" if wrong
        else f"every product uses {ji['identity_tenant']}, like the Joule instance")
    tiers = [p["id"] for p in d["products"] if p["tier"] != ji["tier"]]
    add("F02", "FAIL" if tiers else "OK",
        f"{ji['name']} is {ji['tier']} but serves {', '.join(tiers)}" if tiers
        else f"all products are {ji['tier']}, like {ji['name']}")
    gid = d["identity"].get("global_user_id")
    add("F03", "OK" if gid == "user_uuid" else "FAIL",
        f"users are matched on the Global User ID ({gid})" if gid == "user_uuid"
        else f"users are matched on {gid}, not the Global User ID")
    sync = d["identity"].get("role_sync")
    add("F04", "OK" if sync else "FAIL",
        f"role assignments reach Work Zone: {sync}" if sync else "no role sync: Joule can't tell which functions a user may use")
    used = {f.get("product") for f in d["functions"].values() if f.get("product")}
    for p in d["products"]:
        if p["id"] not in used:
            continue
        dest = p.get("destination") or {}
        auth = dest.get("authentication")
        if auth == "PrincipalPropagation":
            add("F05", "OK", f"{dest['name']} to {p['id']} runs as the signed-in user ({auth})")
        else:
            add("F05", "FAIL", f"{dest.get('name')} to {p['id']} uses {auth}: every call runs as "
                               f"{d.get('technical_user') or 'one shared user'}")
        if dest.get("proxy") == "OnPremise":
            ok = bool(dest.get("cloud_connector") and dest.get("location_id"))
            add("F06", "OK" if ok else "FAIL",
                f"{p['id']} reached through {dest.get('cloud_connector')} (location {dest.get('location_id')})"
                if ok else f"{p['id']} is OnPremise but names no Cloud Connector or location ID")
    for name, f in d["functions"].items():
        if f["kind"] == "transactional":
            add("F07", "OK" if f.get("confirm") else "FAIL",
                f"{name} asks the user to confirm" if f.get("confirm") else f"{name} changes data without a confirmation step")
            flag = f.get("auth_flag")
            for role, funcs in d["roles"].items():
                if name not in funcs:
                    continue
                holders = [u for u, info in d["users"].items() if role in info["roles"]]
                lacking = [u for u in holders if flag and not info_flag(d, u, flag)]
                if lacking:
                    add("F08", "WARN", f"role {role} offers {name} to {', '.join(lacking)}, who lack {flag} in SAP")
                else:
                    add("F08", "OK", f"role {role} offers {name} only to users who hold {flag} in SAP")
    for doc in d["documents"]:
        add("F09", "OK" if doc.get("owner") else "WARN",
            f"{doc['id']} owned by {doc['owner']}" if doc.get("owner") else f"{doc['id']} has no owner to keep it current")
    pc = d.get("privacy_contact")
    add("F10", "OK" if pc else "WARN",
        f"conversation data requests go to {pc}" if pc else "no one named for conversation data requests (export, deletion)")
    return out


def info_flag(d, user, flag):
    return bool(d["users"][user]["sap_auth"].get(flag))


# ---------------------------------------------------------------- trace

def words(text):
    return set(re.findall(r"[a-z]+", text.lower()))


def match(d, allowed, text):
    """Course stand-in for scenario matching: most keyword hits wins, ties go to catalog order."""
    w = words(text)
    best, score = None, 0
    for name in d["functions"]:
        if name not in allowed:
            continue
        hits = sum(1 for k in d["functions"][name]["keywords"] if k in w)
        if hits > score:
            best, score = name, hits
    return best, score


def trace(d, req):
    hops = []

    def hop(step, frm, to, verdict, text):
        hops.append({"step": step, "from": frm, "to": to, "verdict": verdict, "text": text})

    ji = d["joule_instance"]
    user = d["users"].get(req["user"])
    if user is None:
        hop("auth", "Joule client", "Identity Authentication", "DENY", f"{req['user']} is unknown")
        return hops, "REFUSED"
    if user["identity_tenant"] != ji["identity_tenant"]:
        hop("auth", "Joule client", "Identity Authentication", "DENY",
            f"{req['user']} signs in to {user['identity_tenant']}, but {ji['name']} trusts {ji['identity_tenant']}")
        return hops, "REFUSED"
    hop("auth", "Joule client", "Identity Authentication", "OK",
        f"{ji['identity_tenant']} issues an OIDC token for {req['user']}")
    allowed = []
    for role in user["roles"]:
        allowed += [f for f in d["roles"].get(role, []) if f not in allowed]
    if not d["identity"].get("role_sync"):
        allowed = []
    hop("functions", "Joule", "Work Zone", "OK",
        f"roles {', '.join(user['roles'])} give {len(allowed)} function(s)")
    name, score = match(d, allowed, req["text"])
    full, full_score = match(d, list(d["functions"]), req["text"])
    if name is None or (full != name and full_score > score):
        if full:
            hop("catalog", "Joule", "Scenario catalog", "NONE",
                f"best match {full} is not among this user's functions")
            hop("reply", "Joule", "Joule client", "OK", "Joule says it can't do that for this user")
            return hops, "NOT OFFERED"
        hop("catalog", "Joule", "Scenario catalog", "NONE", "no scenario matches")
        hop("reply", "Joule", "Joule client", "OK", "Joule says it has no answer")
        return hops, "NO SCENARIO"
    f = d["functions"][name]
    hop("catalog", "Joule", "Scenario catalog", "OK", f"scenario {name} ({f['kind']})")
    if name == "search_documents":
        w = words(req["text"])
        docs = sorted(d["documents"], key=lambda x: -sum(k in w for k in x["keywords"]))
        doc = docs[0] if docs and any(k in w for k in docs[0]["keywords"]) else None
        if doc is None:
            hop("grounding", "Joule", "Document grounding", "NONE", "no document matches")
            hop("reply", "Joule", "Joule client", "OK", "Joule says it has no answer")
            return hops, "NO SCENARIO"
        hop("grounding", "Joule", "Document grounding", "OK", f"{doc['id']} from {doc['repository']}")
        hop("llm", "Joule", "Dialog model", "OK", "answers from the document, with its title as source")
        hop("reply", "Joule", "Joule client", "OK", f"\"{doc['text']}\" ({doc['title']})")
        return hops, "ANSWERED"
    if f["kind"] == "navigational":
        hop("llm", "Joule", "Dialog model", "OK", f"chooses {name}")
        hop("reply", "Joule", "Joule client", "OK", f"link to {f['target']}")
        return hops, "NAVIGATED"
    m = re.search(r"\b\d{7,10}\b", req["text"])
    key = m.group(0) if m else None
    hop("llm", "Joule", "Dialog model", "OK",
        f"asks Joule to call {name}" + (f" for {key}" if key else ""))
    if f["kind"] == "transactional":
        if f.get("confirm"):
            hop("confirm", "Joule", "Joule client", "OK", f"user confirms: {name} {key}")
        else:
            hop("confirm", "Joule", "Joule client", "SKIP", "no confirmation step")
    product = next(p for p in d["products"] if p["id"] == f["product"])
    dest = product["destination"]
    if dest["authentication"] == "PrincipalPropagation":
        sap_user = req["user"]
        hop("destination", "Joule", "Destination service", "OK",
            f"{dest['name']} exchanges the token at {ji['identity_tenant']} for one {product['id']} accepts ({sap_user})")
    else:
        sap_user = d.get("technical_user") or "TECHNICAL"
        hop("destination", "Joule", "Destination service", "OK",
            f"{dest['name']} logs on as {sap_user} ({dest['authentication']})")
    if dest.get("proxy") == "OnPremise":
        hop("connector", "Destination service", "Cloud Connector", "OK",
            f"{dest['cloud_connector']} location {dest['location_id']} to {dest['virtual_host']}")
    auth = d["users"][sap_user]["sap_auth"] if sap_user in d["users"] else None
    rows = d["records"].get(f["object"], [])
    if auth is not None:
        visible = [r for r in rows if r.get("channel", r.get("purchasing_org")) in auth.get(f["auth_field"], [])]
    else:
        visible = rows
    who = f"{sap_user}" if auth is not None else f"{sap_user} (sees everything)"
    if f["kind"] == "analytical":
        n = sum(1 for r in visible if "credit" in r.get("problem", ""))
        hop("backend", "Cloud Connector", product["id"], "OK", f"{who} reads {len(visible)} orders")
        hop("llm", "Joule", "Dialog model", "OK", "writes the answer from the result")
        hop("reply", "Joule", "Joule client", "OK", f"{n} order(s) blocked for credit")
        return hops, "ANSWERED"
    rec = next((r for r in rows if r["id"] == key), None)
    if rec is None:
        hop("backend", "Cloud Connector", product["id"], "NONE", f"{key} not found")
        hop("reply", "Joule", "Joule client", "OK", f"{key} not found")
        return hops, "NOT FOUND"
    if rec not in visible:
        hop("backend", "Cloud Connector", product["id"], "DENY",
            f"{sap_user} may not read {key} ({f['auth_field']} {rec.get('channel', rec.get('purchasing_org'))})")
        hop("reply", "Joule", "Joule client", "OK", f"you are not authorized to see {key}")
        return hops, "REFUSED"
    if f["kind"] == "transactional":
        if auth is not None and not auth.get(f.get("auth_flag")):
            hop("backend", "Cloud Connector", product["id"], "DENY", f"{sap_user} lacks {f['auth_flag']}")
            hop("reply", "Joule", "Joule client", "OK", f"you are not authorized to change {key}")
            return hops, "REFUSED"
        hop("backend", "Cloud Connector", product["id"], "OK", f"{who} changes {key}; SAP logs {sap_user}")
        hop("reply", "Joule", "Joule client", "OK", f"done: {name} {key}")
        if sap_user != req["user"]:
            return hops, "CHANGED AS " + sap_user
        return hops, "CHANGED" if f.get("confirm") else "CHANGED UNCONFIRMED"
    hop("backend", "Cloud Connector", product["id"], "OK", f"{who} reads {key}")
    hop("reply", "Joule", "Joule client", "OK", f"{key}: {rec['partner']}, {rec['problem']}")
    if auth is None:
        return hops, "SHOWN AS " + sap_user
    return hops, "SHOWN"


def mermaid(req, hops):
    alias = {"User": "U", "Joule client": "C", "Identity Authentication": "IAS", "Joule": "J",
             "Work Zone": "WZ", "Scenario catalog": "SC", "Document grounding": "DG",
             "Dialog model": "LLM", "Destination service": "D", "Cloud Connector": "CC"}
    lines = ["sequenceDiagram", "  participant U as User " + req["user"]]
    seen = {"User"}
    order = ["Joule client", "Identity Authentication", "Joule", "Work Zone", "Scenario catalog",
             "Document grounding", "Dialog model", "Destination service", "Cloud Connector"]
    names = {h["from"] for h in hops} | {h["to"] for h in hops}
    for n in order + sorted(names - set(order)):
        if n in names and n not in seen:
            lines.append(f"  participant {alias.get(n, n.replace('-', ''))} as {n}")
            seen.add(n)
    lines.append(f"  U->>C: {short(req['text'])}")
    for h in hops:
        a = alias.get(h["from"], h["from"].replace("-", ""))
        b = alias.get(h["to"], h["to"].replace("-", ""))
        if h["step"] == "reply":
            lines.append(f"  {a}-->>{b}: {short(h['text'])}")
            lines.append(f"  C-->>U: shows the reply")
        else:
            lines.append(f"  {a}->>{b}: {h['step']} {h['verdict']}: {short(h['text'])}")
    return "\n".join(lines) + "\n"


def short(t, n=60):
    t = t.replace('"', "'").replace(";", ",").replace("#", "no. ")
    return t if len(t) <= n else t[: n - 3] + "..."


# ---------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--init", action="store_true")
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--design")
    ap.add_argument("--review", action="store_true")
    ap.add_argument("--trace", action="store_true")
    ap.add_argument("--only")
    ap.add_argument("--mermaid")
    a = ap.parse_args()

    if a.init:
        for name, data in (("joule_flow_draft.json", make_draft()), ("joule_flow_reviewed.json", REVIEWED)):
            p = HERE / name
            if p.exists() and not a.force:
                print(f"KEEP  {p.name} exists (add --force to overwrite)")
                continue
            p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
            print(f"WROTE {p.name}")
        return 0
    if not a.design:
        ap.error("give --init, or --design FILE with --review, --trace or --mermaid")
    try:
        d = json.loads(Path(a.design).read_text(encoding="utf-8"))
    except FileNotFoundError:
        print(f"No file {a.design}. Run: python unit23/joule_flow.py --init")
        return 1
    except json.JSONDecodeError as e:
        print(f"{a.design} is not valid JSON: line {e.lineno}, column {e.colno}: {e.msg}")
        return 1
    rc = 0
    if a.review:
        res = review(d)
        for rule, verdict, text in res:
            print(f"{rule}  {verdict:<4}  {text}")
        n = {v: sum(1 for r in res if r[1] == v) for v in ("OK", "WARN", "FAIL")}
        print(f"\n{n['OK']} OK, {n['WARN']} WARN, {n['FAIL']} FAIL")
        if n["FAIL"]:
            rc = 2
    if a.trace:
        log = []
        good = 0
        reqs = [r for r in d["requests"] if not a.only or r["id"] == a.only]
        if not reqs:
            print(f"No request {a.only} in {a.design}")
            return 1
        for req in reqs:
            hops, result = trace(d, req)
            label = d["users"].get(req["user"], {}).get("label", "unknown user")
            print(f"\n{req['id']}  {req['user']} {label}: \"{req['text']}\"")
            for i, h in enumerate(hops, 1):
                print(f"  {i:>2} {h['step']:<11} {h['verdict']:<5} {h['text']}")
            ok = result == req.get("expect")
            good += ok
            print(f"  Result: {result}  (expected {req.get('expect')}: {'as designed' if ok else 'CHECK THIS'})")
            log.append({"request": req["id"], "user": req["user"], "result": result,
                        "expected": req.get("expect"), "hops": hops})
        out = HERE / "joule_trace.jsonl"
        out.write_text("".join(json.dumps(x) + "\n" for x in log), encoding="utf-8")
        print(f"\n{good} of {len(reqs)} requests behave as expected. Log: unit23/{out.name}")
    if a.mermaid:
        req = next((r for r in d["requests"] if r["id"] == a.mermaid), None)
        if req is None:
            print(f"No request {a.mermaid} in {a.design}")
            return 1
        hops, _ = trace(d, req)
        text = mermaid(req, hops)
        p = HERE / f"joule_{req['id']}.mmd"
        p.write_text(text, encoding="utf-8")
        print(text + f"WROTE unit23/{p.name}")
    return rc


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 3: Write the two designs

Run:

```bash
python unit23/joule_flow.py --init
```

```text
WROTE joule_flow_draft.json
WROTE joule_flow_reviewed.json
```

Open `unit23/joule_flow_reviewed.json`. It is Calder's reviewed design: Joule instance `joule-prod` in subaccount `calder-ai-prod` on identity tenant `calder-ias`, the S/4HANA Private Edition system `S4P` reached through destination `S4_ODATA` and Cloud Connector `SCC-RK-P`, SuccessFactors Employee Central on the same tenant, five Joule functions, two roles, three users and six test requests. `joule_flow_draft.json` is a partner's first draft of the same design.

> **Note** Running `--init` again keeps your files and prints `KEEP`. Add `--force` only if you want to start over.

#### Step 4: Review the partner's draft

Run:

```bash
python unit23/joule_flow.py --design unit23/joule_flow_draft.json --review
```

```text
F01  FAIL  products on another identity tenant (a separate Joule instance): SF-EC, S4Q
F02  FAIL  joule-prod is production but serves S4Q
F03  OK    users are matched on the Global User ID (user_uuid)
F04  OK    role assignments reach Work Zone: Identity Provisioning from S4P
F05  FAIL  S4_ODATA to S4P uses BasicAuthentication: every call runs as TU_JOULE
F06  OK    S4P reached through SCC-RK-P (location RK)
F07  FAIL  release_credit_block changes data without a confirmation step
F08  WARN  role JOULE_O2C_CLERK offers release_credit_block to 00100265, 00100266, who lack credit_release in SAP
F08  OK    role JOULE_CREDIT_ANALYST offers release_credit_block only to users who hold credit_release in SAP
F09  WARN  DOC-CREDIT-01 has no owner to keep it current
F10  WARN  no one named for conversation data requests (export, deletion)

4 OK, 3 WARN, 4 FAIL
```

The exit code is 2. Where each rule comes from:

| Rule | Checks | Source |
| --- | --- | --- |
| F01 | Every product uses the Joule instance's identity tenant | SAP Learning, unified instance |
| F02 | One Joule instance serves one tier | SAP Learning: one production and one non-production tenant |
| F03 | Users matched on the Global User ID | SAP Learning, unified instance |
| F04 | Role assignments reach Work Zone | SAP IAM reference architecture (Identity Provisioning) |
| F05 | Back-end destinations use principal propagation | SAP IAM reference architecture |
| F06 | Private systems name a Cloud Connector and location ID | SAP Private Edition reference architecture |
| F07 | Transactional functions confirm before changing data | SAP golden path for Joule skills |
| F08 | A role offers a transactional function only to users who hold the SAP authorization | Course rule |
| F09 | Every grounding document has an owner | Course rule |
| F10 | Someone handles conversation data requests | Course rule, from the feature scope description's retrieval and deletion requests |

#### Step 5: Trace the draft and see what the failures do

Run:

```bash
python unit23/joule_flow.py --design unit23/joule_flow_draft.json --trace --only R03
```

```text
R03  00100266 inside sales rep: "Show me order 1000002"
   1 auth        OK    calder-ias issues an OIDC token for 00100266
   2 functions   OK    roles JOULE_O2C_CLERK give 5 function(s)
   3 catalog     OK    scenario get_sales_order (informational)
   4 llm         OK    asks Joule to call get_sales_order for 1000002
   5 destination OK    S4_ODATA logs on as TU_JOULE (BasicAuthentication)
   6 connector   OK    SCC-RK-P location RK to s4p-api:443
   7 backend     OK    TU_JOULE (sees everything) reads 1000002
   8 reply       OK    1000002: Hallam Fluid Systems, credit block
  Result: SHOWN AS TU_JOULE  (expected REFUSED: CHECK THIS)

0 of 1 requests behave as expected. Log: unit23/joule_trace.jsonl
```

The inside sales rep works in channel 10 only, and order 1000002 is Hallam's distributor order in channel 20. Every hop says OK, and the data still leaks, because the back end checked `TU_JOULE`, not the rep.

Now run all six requests on the draft:

```bash
python unit23/joule_flow.py --design unit23/joule_flow_draft.json --trace
```

The last line reads `3 of 6 requests behave as expected.` R05 ends `CHANGED AS TU_JOULE` (the credit analyst's release is logged under the technical user, and nobody confirmed it) and R06 ends `CHANGED AS TU_JOULE` (the clerk released a credit block: the role offered the function, no confirmation stopped it, and SAP saw the technical user).

#### Step 6: Review and trace the reviewed design

Run:

```bash
python unit23/joule_flow.py --design unit23/joule_flow_reviewed.json --review --trace
```

The review ends `10 OK, 0 WARN, 0 FAIL` with exit code 0, and the trace ends `6 of 6 requests behave as expected.` Look at the two that matter most:

```text
R03  00100266 inside sales rep: "Show me order 1000002"
   ...
   5 destination OK    S4_ODATA exchanges the token at calder-ias for one S4P accepts (00100266)
   6 connector   OK    SCC-RK-P location RK to s4p-api:443
   7 backend     DENY  00100266 may not read 1000002 (sales_channels 20)
   8 reply       OK    you are not authorized to see 1000002
  Result: REFUSED  (expected REFUSED: as designed)

R06  00100265 customer service clerk: "Release the credit block on order 1000002"
   1 auth        OK    calder-ias issues an OIDC token for 00100265
   2 functions   OK    roles JOULE_O2C_CLERK give 4 function(s)
   3 catalog     NONE  best match release_credit_block is not among this user's functions
   4 reply       OK    Joule says it can't do that for this user
  Result: NOT OFFERED  (expected NOT OFFERED: as designed)
```

R03 is stopped by SAP, the control. R06 is stopped earlier by role content, the convenience. If the role content were wrong, R06 would reach SAP as the clerk and SAP would refuse it there, because the clerk lacks `credit_release`.

> **Note** These results come from made-up data in a course stand-in. They show the order of decisions and where each fails, not how SAP's own Joule behaves on a real tenant.

#### Step 7: Draw the diagram

Run:

```bash
python unit23/joule_flow.py --design unit23/joule_flow_reviewed.json --mermaid R05
```

The script prints a Mermaid sequence diagram and writes `unit23/joule_R05.mmd`. To see it, paste the text into a Markdown file in GitHub inside a ` ```mermaid ` block, or into the free Mermaid Live Editor at mermaid.live. This is the drawing to put in a design document: one per request pattern, generated from the same file the review checked, so the picture can't drift from the design.

#### Step 8: Save your work in Git

```bash
git add unit23/joule_flow.py unit23/joule_flow_draft.json unit23/joule_flow_reviewed.json unit23/joule_R05.mmd
git commit -m "Unit 23: Joule request path, review and trace"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `REVIEWED` and `make_draft()` | Calder's reviewed design, and the partner's draft with its faults |
| `review()` | Rules F01 to F10; FAIL sets exit code 2 |
| `trace()` | One request through sign-in, functions, catalog, grounding or function call, confirmation, destination, Cloud Connector, back end and reply |
| `match()` | Course stand-in for scenario matching: the allowed function with most keyword hits; if a better match exists outside the user's list, the result is NOT OFFERED |
| Back-end check | Reads the effective SAP user's authorizations: the signed-in user with principal propagation, or the technical user, who sees everything |
| `mermaid()` | Turns a trace into a sequence diagram |
| `joule_trace.jsonl` | One line per request with every hop, for your evidence pack |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your path | Follow [Set up your computer](https://erpfde.com/topics/set-up-your-computer/); on macOS try `python3` |
| `No file unit23/joule_flow_draft.json` | You skipped Step 3, or ran from another folder | Run from `orchestrate-course`: `python unit23/joule_flow.py --init` |
| `is not valid JSON: line 40, column 5` | An edit broke the file, often a missing comma | Fix the line shown, or run `--init --force` for fresh files |
| `KEEP joule_flow_reviewed.json exists` | Your files are kept on purpose | Add `--force` only to start over |
| `No request R09 in ...` | That request ID isn't in the file | Check the `requests` list |
| A request you added shows `NO SCENARIO` | None of its words match any function's keywords | Add a keyword to the function, or reword the request |
| `ModuleNotFoundError` | You are not in the virtual environment, or the code was pasted wrong | Turn on `.venv` (Step 1) and paste the script again; it needs no libraries |
| A proxy or network error | Not from this script, which uses no network | Check that you ran `joule_flow.py`, not another file |

### The SAP way

As of 28 November 2026, from SAP's pages:

- **Prerequisites for one Joule.** A licensed SAP product that supports Joule and already uses Cloud Identity Services, an enterprise global account with Joule and Work Zone entitlements, one Work Zone edition per Joule instance (standard, advanced or SuccessFactors), and the same identity tenant and Global User ID for all participating applications ([SAP Learning](https://learning.sap.com/courses/setting-up-joule-across-your-organizational-system-landscapes/setting-up-a-unified-joule-instance)).
- **S/4HANA Cloud Private Edition.** For RISE with SAP customers: the Joule service with its foundation plan, Work Zone standard edition as the launchpad that surfaces Joule, Identity Authentication for sign-in, Identity Provisioning to sync users and roles from the S/4HANA system, the Cloud Connector, and the OData services behind each transactional task activated in the back end ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/ebe268), updated 29 October 2025).
- **S/4HANA Cloud Public Edition.** Joule is natively integrated; setup is done per tenant and can't be transported ([same page](https://architecture.learning.sap.com/docs/ref-arch/ebe268)).
- **Custom skills.** Built in Joule Studio with action projects that wrap OData APIs; destinations configured in the SAP Business AI Platform cockpit; a standalone environment for testing and a shared environment for production; confirmation steps for create, update and delete ([golden path](https://architecture.learning.sap.com/docs/golden-path/ai-golden-path/build-and-deliver/joule-skills), updated 26 October 2026). The builder's detail is in [Joule and Joule Studio](https://erpfde.com/topics/joule-and-joule-studio/).
- **Agents.** Joule Studio Classic agents use models from SAP AI Core and customer document grounding, with back-end calls through the Connectivity and Destination services ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/ff07b1), updated 21 October 2026). [Joule agents and agent orchestration](https://erpfde.com/topics/joule-agents-and-agent-orchestration/) covers how Joule hands work to them.
- **Licensing.** The 2026 feature scope description says some features need a separate subscription licence. [AI Units and SAP's commercial model for AI](https://erpfde.com/topics/ai-units-and-commercial-model/) covers Joule Base, Premium AI and AI Units.

[Joule authorizations, data access and security](https://erpfde.com/topics/joule-authorizations-and-security/) covers the security review and [Activating Joule across SAP products](https://erpfde.com/topics/activating-joule-across-products/) the setup sequence; [Document grounding for Joule](https://erpfde.com/topics/joule-document-grounding/) covers the document sources.

### Build vs. SAP

| Need | Use Joule | Build your own assistant on BTP | Why |
| --- | --- | --- | --- |
| Questions and tasks inside SAP cloud applications | Yes | No | Joule is already embedded, signed in and role-aware |
| One assistant across S/4HANA, SuccessFactors and other SAP products | Yes, one instance per tier | Only if Joule doesn't cover a product you need | Joule's shared identity and role content do the hard part |
| A skill SAP doesn't ship | Joule Studio skill or agent | Pro-code agent connected to Joule | Keep the user inside Joule; [where should an agent live](https://erpfde.com/topics/where-should-an-agent-live/) has the decision method |
| Full control of model, prompts and logs | Limited: SAP runs the model and stores conversations | Yes | A regulated process may need logs and models you operate |
| Users who live in another tool (Teams, a CRM) | Joule's integrations, or A2A through the Agent Gateway | An agent in that tool calling SAP | Unit 15 compares the platforms |

### Architecture view

**Where it sits.** At Calder, Joule runs as SAP's service, attached to subaccount `calder-ai-prod`. Users sign in through `calder-ias`, federated to Calder's corporate sign-in. Work Zone standard edition sits in the same global account. S/4HANA `S4P` is reached through destination `S4_ODATA` and Cloud Connector `SCC-RK-P`, as in the [connectivity design](https://erpfde.com/topics/btp-connectivity/). SuccessFactors Employee Central joins the same Joule on the same tenant. Augsburg's ECC system `ECP` has no Joule until the July 2027 rollout. The sequence in [How it works](#d-how-it-works) is the request-level view.

```mermaid
flowchart LR
  U[Calder users] --> IAS[calder-ias<br/>Identity Authentication]
  IAS --> J[joule-prod<br/>SAP-run service]
  J --> WZ[Work Zone<br/>role content]
  J --> M[Dialog model<br/>generative AI hub]
  J --> D[Destination S4_ODATA<br/>PrincipalPropagation]
  D --> CC[SCC-RK-P] --> S4P[S4P S/4HANA PCE]
  J --> SF[SuccessFactors EC]
  IPS[Identity Provisioning] --> WZ
  S4P -. users and roles .-> IPS
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Identity | One identity tenant per tier; every back-end call as the user | Second Joule; data seen through a technical user |
| Authorization | Role content in line with the SAP role matrix, checked each release | Functions offered to the wrong people; noisy refusals |
| Latency | A read answered within a few seconds; long tasks asynchronous | Users stop asking; timeouts on transactional calls |
| Availability | Joule and its dependencies (identity, Work Zone, Cloud Connector) as available as the back end | One missing piece stops every request |
| Data protection | Processing location and retention agreed in writing; deletion requests owned | Privacy findings; requests nobody answers |
| Cost | Base and premium use known per product | AI Units consumed by features nobody planned |

**Integration and identity.** The user's identity starts as an OIDC token from `calder-ias` and reaches `S4P` through a token exchange in the Destination service; the Cloud Connector passes it on for principal propagation. Users and role assignments flow from `S4P` to Work Zone through Identity Provisioning. Business calls use the OData services each function needs, activated in `S4P`. Document grounding reads from the repositories SAP supports (SharePoint, Google Drive, Work Zone).

**The decision to record.**

- **Context:** Joule for customer service and credit in `CP10`; SuccessFactors already on `calder-ias`; a partner proposed a technical user for `S4_ODATA` "to avoid principal propagation setup", and a separate identity tenant for HR.
- **Options:** (A) principal propagation and one tenant, as SAP documents; (B) technical user and two tenants, faster to start; (C) A for production, B for a pilot only.
- **Decision:** A. B leaks data across sales channels (trace R03) and records the technical user for every change (R05, R06); C would build a pilot whose test results mean nothing for production.
- **Consequences:** the Cloud Connector's principal propagation and Identity Provisioning must be set up before the pilot; HR joins the existing tenant instead of getting its own.

**What a design review will ask.**

1. For each request pattern, which component decides, and where does the user's identity travel?
2. Is any back-end destination using a technical user, and what does SAP's change log record for a Joule action?
3. Who keeps role content in line with the SAP role matrix, and how is drift found?
4. Where are conversations processed and how long are they kept?
5. Does the tenant use destinations or the Agent Gateway for back-end calls, and what changes when that moves?

### Production concerns

- **Security and SAP authorizations.** Principal propagation on every destination Joule uses; no shared users. Joule's offer of a function is never the control; SAP's check is. [Joule authorizations, data access and security](https://erpfde.com/topics/joule-authorizations-and-security/) turns this into a review with attack tests.
- **Evaluation.** Test each function with at least two users who differ in authorization, as R03 and R06 do. Keep the requests as a regression set and rerun after every role or release change.
- **Change.** SAP's 2025 feature scope description says capabilities are bundled and updated automatically. New SAP skills can appear in your users' catalog without a transport; review the release notes for what the next release adds to role content.
- **Data protection.** Agree retention and processing location for conversations and grounding with SAP in writing; name the owner for export and deletion requests (rule F10).
- **Operations.** Monitor the pieces you run: Identity Provisioning jobs, the Cloud Connector, destination certificates. A failed sync looks like Joule "forgetting" functions.
- **Cost.** Know which functions are Joule Base and which consume AI Units before switching them on.
- **Clean core.** Joule calls released OData services; it gives no reason to open unreleased interfaces.

### Where AI fits

The dialog model is the one AI component in the path, and the design's job is to box it in. It picks among functions, but only the user's; it writes answers, but from grounded documents and returned data; it asks for calls, but the call carries the user's identity to SAP's checks. The new risk is the model making a confident wrong choice, so the architecture puts every irreversible decision somewhere deterministic: role content, confirmation, the back end.

Two things change as SAP moves to Joule Work and the Agent Gateway. Agents become one more consumer on the same path, so their calls need the same identity design ([agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/)). And more of the path becomes SAP-managed, which means fewer components you configure and more you must ask SAP about.

### Pitfalls

- **Drawing Joule as one box.** The review can't find the identity hop, so nobody checks it.
- **A technical user "for the pilot".** The pilot proves nothing about who sees what, and it often stays.
- **A second identity tenant for one product.** It creates a second Joule, not a second door to the same one.
- **Testing with one super user.** Every request works, so no authorization is tested. Test with two users who differ.
- **Trusting hidden functions.** Role content can drift from the SAP role matrix; the back end must still refuse.
- **Non-production systems on the production Joule.** Test data and production users meet in one assistant.
- **No owner for grounding documents.** Joule answers confidently from an old policy.
- **Assuming the region.** Conversations and grounding may be processed elsewhere than your SAP systems; ask.

### Exercise

Add Calder's buyer to the design: a read function for purchase orders, a role for it, and two test requests.

1. Copy the reviewed design to a new file:
   - **Windows (PowerShell):** `Copy-Item unit23/joule_flow_reviewed.json unit23/joule_flow_exercise.json`
   - **macOS / Linux:** `cp unit23/joule_flow_reviewed.json unit23/joule_flow_exercise.json`
2. Open `unit23/joule_flow_exercise.json`. In `"functions"`, after the `"release_credit_block"` block, type a comma after its closing `}` and add:

   ```json
   "get_purchase_order": {"kind": "informational", "keywords": ["show", "purchase", "order"],
     "product": "S4P", "object": "purchase_orders", "auth_field": "purchasing_orgs"}
   ```

3. In `"roles"`, add a role (comma after the previous entry first):

   ```json
   "JOULE_P2P_BUYER": ["get_purchase_order"]
   ```

4. In `"users"`, add buyer `00100211`:

   ```json
   "00100211": {"label": "buyer", "identity_tenant": "calder-ias", "roles": ["JOULE_P2P_BUYER"],
     "sap_auth": {"purchasing_orgs": ["PUUS"]}}
   ```

5. In `"records"`, after the `"sales_orders"` list, add:

   ```json
   "purchase_orders": [
     {"id": "4500000002", "partner": "Orrin Motor Works", "purchasing_org": "PUUS",
      "problem": "no supplier confirmation"}
   ]
   ```

6. In `"requests"`, add two requests:

   ```json
   {"id": "R07", "user": "00100211", "text": "Show me purchase order 4500000002", "expect": "SHOWN"},
   {"id": "R08", "user": "00100265", "text": "Show me purchase order 4500000002", "expect": "NOT OFFERED"}
   ```

7. Run the review and the trace:

   ```bash
   python unit23/joule_flow.py --design unit23/joule_flow_exercise.json --review --trace
   ```

8. Draw R07: `python unit23/joule_flow.py --design unit23/joule_flow_exercise.json --mermaid R07`.
9. Change `"purchasing_orgs": ["PUUS"]` to `["PUDE"]` for the buyer and run the trace with `--only R07`. It should end `REFUSED`: the buyer's Joule function is offered, but SAP refuses a purchase order outside the buyer's purchasing organization. Change it back.
10. Commit `joule_flow_exercise.json` and `joule_R07.mmd`.

**Done when:** the review ends `10 OK, 0 WARN, 0 FAIL`, the trace ends `8 of 8 requests behave as expected`, `unit23/joule_R07.mmd` exists, and you can say in one sentence why R08 stops at the catalog and step 9 stops at SAP. Keep the design file: later Unit 23 topics on activation and authorizations extend it, and the Architect capstone (Unit 32) collects it.

### Going further

For readers who want SAP's primary material on the identity mechanics behind the path.

The token exchange at the heart of principal propagation is easy to describe and fiddly to operate. Three primary sources take you further:

- [Identity and Access Management for SAP Joule](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f): the full runtime flow, the supported SAML and OIDC flows (SP-initiated and resource-provider-initiated; IdP-initiated SAML technically possible but not recommended), and how group attributes from the Identity Directory are mapped into tokens. Read it before choosing how your corporate identity provider federates.
- [Joule in S/4HANA Cloud Private and Public Edition](https://architecture.learning.sap.com/docs/ref-arch/ebe268): the Private Edition prerequisites, including minimum UI5 versions per release and the Cloud Connector tunnel, and why Public Edition setup is per tenant.
- [Integrating and Extending Joule](https://architecture.learning.sap.com/docs/ref-arch/464deb): the catalog and grounding side of the flow, and links into SAP's Work Zone and Common Data Model pages that define role content.

Two hard edges worth knowing. First, the Global User ID: SAP Learning warns that inconsistent IDs across applications cause functional problems, and they are often invisible until two products disagree about one person. Second, role content and SAP roles are maintained in different places by different teams; plan a check that compares them every release, the way rule F08 does in the lab.

### Check yourself

1. In SAP's documented flow, what decides which Joule functions a user can use in a session?
   - A. The dialog model, from the words in the user's question
   - B. Work Zone combining the user's roles with role content
   - C. The S/4HANA system, after the function has been called
   - D. The Cloud Connector, from the location ID it is given

   Answer: B. SAP's IAM reference architecture has Joule ask the Work Zone navigation service to combine the user, their role assignments and the Common Data Model role content. The model then chooses only among those functions.

2. What does the Destination service do in a principal propagation call from Joule to S/4HANA?
   - A. It stores the user's password and sends it with every call
   - B. It replaces the user with a shared technical user for speed
   - C. It exchanges the user's token for one the target system accepts
   - D. It sends the call to the model to decide whether it is allowed

   Answer: C. The Destination service exchanges Joule's user token at Identity Authentication for a token the target application accepts. S/4HANA then applies that user's own authorizations.

3. In the lab's draft, every hop for R03 says OK, yet the result is wrong. Why?
   - A. The scenario matcher picked the wrong function for the question
   - B. The Cloud Connector routed the call to the quality system
   - C. The dialog model invented the order data it showed
   - D. The back end checked TU_JOULE, who may see every channel

   Answer: D. With BasicAuthentication the destination logs on as the technical user, so S/4HANA checks TU_JOULE's authorizations instead of the rep's. Each component did its job; the design gave the wrong identity to the one that decides.

4. Your trace shows R06 as NOT OFFERED in the reviewed design. What would happen if role content wrongly offered the function to the clerk?
   - A. SAP would refuse the call, because the clerk lacks credit_release
   - B. The block would be released, because Joule offered the function
   - C. Joule would fail to start because the role content is invalid
   - D. The model would decline, because it knows the credit policy

   Answer: A. With principal propagation the call reaches SAP as the clerk, and SAP's check refuses it. Role content is a convenience layer; the back end's authorization is the control, which is why both are tested.

5. A partner wants SuccessFactors on its own identity tenant "to keep HR separate". What does SAP's unified guidance imply?
   - A. HR questions will become faster because they get their own model
   - B. It creates a separate Joule instance instead of joining the shared one
   - C. Nothing changes, because Joule ignores identity tenants entirely
   - D. HR data will be copied into the S/4HANA system for grounding

   Answer: B. SAP Learning says all applications in one Joule must use the same identity tenant, and different tenants mean separate Joule instances. Users then get two assistants and the setup is done twice.

6. Which part of the Joule request path is not deterministic configuration your team owns?
   - A. The role content that maps roles to Joule functions
   - B. The destination's authentication type and Cloud Connector
   - C. The dialog model's choice of answer or function call
   - D. The SAP back end's authorization check on the record

   Answer: C. The dialog model is the one component that guesses. A defensible design boxes it in: it chooses only among the user's functions, and its calls still run as the user against SAP's checks.

7. SAP's Joule Work lesson describes an Agent Gateway on the back-end hop, while older pages describe destinations. What should an architect do?
   - A. Assume the Agent Gateway is live everywhere and drop destinations
   - B. Ignore both, since principal propagation is no longer needed
   - C. Wait to design anything until SAP retires one of the two paths
   - D. Ask which path the tenant uses and design identity for that one

   Answer: D. Both descriptions keep the same principle, the back end sees the signed-in user, but they put it in different components. The lesson gives no release status, so the tenant's actual path decides what you configure and monitor.

8. A design document needs retention and processing location for Joule conversations. Where should the answer come from?
   - A. SAP's feature scope description, which lists the retention periods
   - B. The dialog model, by asking it in a test conversation
   - C. SAP in writing, since the pages read state no periods or regions
   - D. The Cloud Connector logs, which keep every conversation

   Answer: C. The 2026 feature scope description says history is captured and deletion can be requested, but gives no retention periods or regions. That makes it a question to settle with SAP and record, not a value to assume.

## Sources

- [Integrating and Extending Joule, SAP's AI Copilot (SAP Architecture Center, updated 16 March 2026)](https://architecture.learning.sap.com/docs/ref-arch/464deb): read 2026-11-28; four capability patterns (transactional, navigational, informational, analytical); request flow in five steps (Joule client, Scenario Catalog, Knowledge Catalog and user context, dialog-management LLM from partner models through SAP's AI foundation and generative AI hub, grounded answer or Joule function call to the back end, filtered response); partner contracts prohibit training on customer data; Cloud Identity Services required, one shared instance recommended
- [Identity and Access Management for SAP Joule (SAP Architecture Center, updated 22 September 2025)](https://architecture.learning.sap.com/docs/ref-arch/ea5d4f): read 2026-11-28; Identity Authentication issues an OIDC token; Work Zone Navigation Service combines user, role assignments and Common Data Model role content to decide the Joule functions a user may use; functions and APIs called through the BTP Destination service with principal propagation (token exchanged at Identity Authentication); Global User ID; Identity Provisioning syncs users and role assignments by SCIM
- [Joule in SAP S/4HANA Cloud Private and Public Edition (SAP Architecture Center, updated 29 October 2025)](https://architecture.learning.sap.com/docs/ref-arch/ebe268): read 2026-11-28; Private Edition for RISE with SAP customers; Joule service (foundation plan), Work Zone standard edition and Cloud Identity Services on BTP; Cloud Connector tunnel; matching OData services activated for transactional tasks; Identity Provisioning syncs users and roles from the S/4HANA system; principal propagation; Public Edition natively integrated, set up per tenant, not transportable
- [Setting Up a Unified Joule Instance (SAP Learning)](https://learning.sap.com/courses/setting-up-joule-across-your-organizational-system-landscapes/setting-up-a-unified-joule-instance): read 2026-11-28; one Joule instance on BTP shared by SAP cloud applications; same Identity Authentication tenant and Global User ID (user_uuid) for all; one production and one non-production tenant; different tenants mean separate Joule instances; one Work Zone edition (standard, advanced or SuccessFactors) per Joule instance; Joule does not bypass the applications' authorizations
- [Understanding Joule's Architecture (SAP Learning, Introducing Joule)](https://learning.sap.com/courses/introducing-joule/understanding-joule-s-architecture_a1ea765b-6dc7-4cd9-b741-2a45d9eb9b3a): read 2026-11-28; Joule Work as experience, build and agent execution layers over a shared foundation (Business Knowledge Graph, Enterprise Knowledge Exploration for document grounding, Agent Gateway through which every request from Joule to an agent or back-end service passes, handling authentication, principal propagation and tool discovery, AI Agent Hub, Task Center); actions traceable to user and role; no status labels
- [Joule Feature Scope Description, version 3.0.0 (help.sap.com, 5 May 2026)](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/Joule_FSD.pdf): read 2026-11-28; conversation history, analytics and feedback captured for auditability; users search conversations, request retrieval or deletion of personal data, download diagnostic traces; analytics by product, scenario and client type; document grounding from SharePoint, Google Drive and Work Zone (DOCX, PDF, PPTX, HTML); some features need a separate licence; no retention periods or regions stated
- [Feature Scope Description for Joule (help.sap.com, 4 September 2025)](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/9c3432ecab90406e99dbc987389334ed.pdf): read 2026-11-28; multitenant SaaS on SAP BTP running on Amazon Web Services; capabilities bundled into one assistant by publish and subscribe, updated automatically; falls back to search over SAP Help Portal content when no intent fits; points to a separate Data Centers Supported by Joule page (not opened)
- [Joule Skills with Joule Studio on SAP Business AI Platform (SAP Architecture Center golden path, updated 26 October 2026)](https://architecture.learning.sap.com/docs/golden-path/ai-golden-path/build-and-deliver/joule-skills): read 2026-11-28; skills also called Joule scenarios; action projects wrap OData APIs; destinations configured in the SAP Business AI Platform cockpit; standalone environment for testing, shared environment for production; confirmation steps for create, update and delete
- [Extend Joule with Joule Studio Classic in SAP Build (SAP Architecture Center, updated 21 October 2026)](https://architecture.learning.sap.com/docs/ref-arch/ff07b1): read 2026-11-28; Joule client as entry point for custom skills and agents; agents use LLMs from SAP AI Core and customer document grounding; back-end calls through the Connectivity and Destination services; Global User ID managed by Identity Authentication
- [Evaluating an End-User Workflow Example (SAP Learning, Guiding AI-driven transformation as an SAP enterprise architect)](https://learning.sap.com/courses/guiding-ai-driven-transformation-as-an-sap-enterprise-architect/evaluating-an-end-user-workflow-example): read 2026-11-28; illustrative walk-through of one prompt: authentication through Identity Authentication, context from vector search and SAP Knowledge Graph, intent inferred and routed, model run through the generative AI hub with guardrails, enterprise data not used for training, actions logged
