# Document grounding for Joule: sources, indexing, access and freshness

> Decide which document sources may feed Joule, how they are read and refreshed and who sees the answers, then review a grounding design before production.

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

Joule can answer questions from your own documents: policies, procedures, handbooks. SAP calls this document grounding. A pipeline reads a document library, such as a SharePoint site, cuts the text into pieces and stores them in a searchable index. When someone asks Joule a question, Joule finds the best pieces and writes its answer from them.

Three facts shape every design decision. The pipeline reads the library with **one technical identity**, not as each user. It copies the library **once a day**, so the index is up to a day behind. And it reads **text**: SAP's setup guide says tables and embedded images aren't supported.

The decision for you: connect a library to Joule only when everyone who can ask Joule may read every document in it, each document has an owner, and the owner accepts that a change takes a day to reach answers.

### Why it matters to the business

Take Calder Pumpworks, the course's fictional pump maker. Its staff ask the same questions every week. What credit limit does a new distributor start with? What is the hotel limit per night? How do I refill the test bench coolant? The answers sit in documents, and people email the credit team, HR or the safety manager to find them. Joule could answer in seconds, from the current document.

The value is real, and so are the risks:

| What goes wrong | Calder example | Cost |
| --- | --- | --- |
| A confidential file sits in a connected library | The credit team's notes on Hallam answered to an inside sales rep | A leak through a chat, hard to detect |
| An old copy beside the new one | The 2024 credit policy answers instead of this year's | Staff act on the wrong limit |
| A change takes a day | The limit changed at 10:00; Joule says the old number all afternoon | A wrong promise to a distributor |
| Key content in a table or a spreadsheet | The hotel limit sits in a table and Joule finds nothing | Staff stop trusting Joule |
| Nobody owns the document | A procedure owned by a technician who left | Outdated steps on a safety task |

None of these is fixed by a better model. They are fixed by choosing sources well and running them like a library: owners, review dates, one copy of each document.

### How SAP does it

As of 28 November 2026, SAP's pages say this:

- **What it is.** The [feature scope description](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/Joule_FSD.pdf) (version 3.0.0, 5 May 2026) lists document grounding as a Joule feature. It names Microsoft SharePoint, Google Drive and SAP Build Work Zone as sources and DOCX, PDF, PPTX and HTML as content types, with automated content updates and custom metadata. SAP's [architecture page](https://architecture.learning.sap.com/docs/ref-arch/464deb) (updated 16 March 2026) places it in Joule's informational pattern, through SAP's Document Grounding service.
- **How it's set up.** SAP's [setup guide](https://community.sap.com/t5/technology-blogs-by-sap/joule-getting-started-with-document-grounding-setup-guide/ba-p/13739501) on SAP Community has you add a Document Grounding entitlement on SAP BTP, register an application in Microsoft Entra ID that may read SharePoint, and create a pipeline for one site or folder.
- **Limits SAP states.** The same guide says up to 2,000 documents, content updated once a day, no manual refresh, tables and embedded images not supported, and English. It is a community post, so treat these as values to confirm for your contract.
- **Who sees what.** Answers to transactional questions run as the user against the SAP system. The grounding pages read for this topic describe the pipeline's own identity, not a per-user check of each document's permissions. For SAP SuccessFactors, SAP's [metadata guide](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-contextualization-aka-metadata-to-your/ba-p/14304077) tags documents with fields such as country and matches them to the employee's profile.
- **Licensing.** The setup guide says the service appears when you hold AI Units. The metadata guide says it is metered monthly by records; the [product page](https://www.sap.com/products/artificial-intelligence/document-grounding.html) lists a flat fee without prices. Ask your account team which applies.

> **Note** **For functional consultants:** the policies and procedures your process relies on become test data. For each process you own, list the five questions users ask most, the document that answers each, and its owner. Those questions become Joule's test set; rerun them after every policy change, because the answer changes a day later, not at once.

### Five decisions before the first pipeline

| Decision | Options | Calder's choice |
| --- | --- | --- |
| Which libraries | Whole intranet, one site, one folder | One curated folder, `CalderPolicies/Joule` |
| Who may read the answers | Everyone on Joule, or a group | Everyone on Joule; narrower libraries stay out until SAP confirms per-user checks |
| How the pipeline reads | A password user, or an application with a secret | An application, limited to the one site |
| How fresh | Daily refresh, or publish changes ahead of their date | Daily; owners publish a changed policy the day before it applies |
| Who owns each document | Nobody, IT, or the process owner | The process owner, named in the register |

The first two decisions carry the risk. A library that holds one confidential file makes Joule a way to read it.

### Questions to ask

Ask your team, partner or SAP account team:

- Which libraries will feed Joule, and can everyone who uses Joule read every document in them today?
- Does Joule check a user's own permission on each document when it answers, or only the pipeline's? Can we have that in writing?
- How many documents per pipeline does our contract allow, and how is grounding metered?
- How long after a document changes or is deleted does Joule stop using the old version?
- Who owns each document, and who removes old copies?
- In which data center is the index kept?
- Which of our important answers sit in tables, spreadsheets or scanned images?

### Common misconceptions

- **"Joule only shows people documents they can open in SharePoint."** The pages read for this topic don't say that. They describe one reading identity per pipeline. Until SAP confirms per-user checks for your source, design as if anyone on Joule can get an answer from any connected document.
- **"Metadata will hide the confidential files."** SAP's metadata feature is described for SuccessFactors HR content. Keep confidential files out of the library.
- **"Joule reads the document live."** It reads an index refreshed once a day.
- **"Delete the file and Joule forgets it."** Not until the next refresh.
- **"More documents give better answers."** Duplicates and old versions give conflicting ones. A support note even describes Joule answering from a single document.
- **"Grounding replaces the policy owner."** It makes the owner more important: a wrong document is now answered at scale.

### Key terms

- **Document grounding:** Joule answering from your own documents, retrieved from a connected repository at question time.
- **Pipeline:** the job that reads one repository, splits the text, and stores it in the index on a schedule.
- **Repository:** the library a pipeline reads, such as a SharePoint site or a Google Drive.
- **Index:** the searchable copy of the documents' text that Joule retrieves from.
- **Refresh:** the pipeline's daily run that brings changes and deletions into the index.
- **Technical identity:** the single account or application a pipeline reads with.
- **Metadata (contextualization):** tags on documents, such as country, that SAP matches to the user's profile for SuccessFactors content.
- **Document register:** the list of connected sources and documents with their owner, audience and review date.

### Check yourself

1. Calder's intranet site holds one folder of credit team notes. Why shouldn't the whole site feed Joule?
   - A. The notes would make the index too large for one pipeline
   - B. Anyone on Joule could get an answer drawn from those notes
   - C. Joule refuses to index any site that has more than one folder
   - D. The notes would slow down every answer for the credit team

   Answer: B. The pipeline reads the site with one technical identity, and the pages read don't describe a per-user check at answer time. A library with one confidential file makes Joule a way to read it.

2. The credit limit for new distributors changed at 10:00. What will Joule most likely say at 14:00 that day?
   - A. The new limit, because Joule reads the source document live each time
   - B. Nothing, because a changed document is removed from the index
   - C. The old limit, until the next daily refresh brings the change in
   - D. Both limits, because it shows every version side by side

   Answer: C. SAP's setup guide says content is updated once a day. Until the refresh runs, the index still holds the old text, so owners publish changes ahead of the date they apply.

3. Which decision belongs to the document's business owner rather than to IT?
   - A. Which Entra ID permission the pipeline's application holds
   - B. Whether the document is current and who may read it
   - C. Which BTP subaccount holds the Document Grounding entitlement
   - D. How often the pipeline refreshes its copy of the library

   Answer: B. IT sets up the pipeline and its credential. Only the owner can say a document is current, retire old copies and confirm everyone on Joule may read it.

4. A partner proposes metadata tags to hide credit notes from sales staff in SharePoint. What is the safer reply?
   - A. Accept it, because metadata filters apply to every repository Joule reads
   - B. Accept it, because the model will not repeat confidential notes
   - C. Reject grounding altogether and answer only from SAP functions
   - D. Keep the notes out of the library; tags are described for HR content

   Answer: D. SAP describes managed metadata with SuccessFactors, matching tags to the employee's profile. It isn't a general way to hide files, so confidential files stay out of connected libraries.

5. Joule can't find the hotel limit, although the travel policy is connected. What is the likely cause?
   - A. The travel policy was written in a PDF file instead of DOCX
   - B. The question was asked before the pipeline was ever created
   - C. The limit sits in a table, which SAP's guide says isn't supported
   - D. Joule only answers travel questions for the HR team itself

   Answer: C. SAP's setup guide says tables and embedded images aren't supported. Important rules should also appear as sentences, which is a change for the document owner.

6. What should you get from SAP in writing before Calder connects a library meant only for one team?
   - A. A promise that the model was trained on Calder's documents
   - B. Whether Joule checks each user's own permission on documents
   - C. The list of Calder users who have asked Joule a question
   - D. The exact wording Joule will use when it answers the team

   Answer: B. The pages read describe the pipeline's identity, not a per-user check. If SAP confirms such a check for your source, narrower libraries become possible; until then they stay out.

## Deep layer

### Mental model

Think of document grounding as **a night copy made by one librarian with one key**.

1. **One key.** The pipeline reads a repository with one identity: an Entra ID application, a technical user, a Work Zone OAuth client. Whatever that key can open is in the index.
2. **A night copy.** The pipeline copies the text once a day. Between copies, the index is a snapshot: changes and deletions arrive at the next run.
3. **Text only.** What becomes searchable is the text the pipeline can extract from supported file types. Tables, images and unsupported files are invisible.

At question time Joule searches the copy, not the repository. So three questions decide a design. What can the key open? How old may the copy be? What text is actually in it? Everything else, from chunking to ranking, is SAP's to run.

[How Joule works](https://erpfde.com/topics/how-joule-works/) placed grounding on the informational path, and [Joule authorizations, data access and security](https://erpfde.com/topics/joule-authorizations-and-security/) set the conservative rule this topic builds on: no source wider than its documents' audience. Here you design and test the sources themselves.

### How it works

#### The pieces

As of 28 November 2026, SAP's [setup guide](https://community.sap.com/t5/technology-blogs-by-sap/joule-getting-started-with-document-grounding-setup-guide/ba-p/13739501) for SharePoint uses these parts:

- **A Document Grounding entitlement** with service plan `data-manager` in the subaccount where Joule runs. The guide says the service shows up in the global account when you hold AI Units.
- **A Document Grounding instance** and a **Cloud Identity Services instance** with plan `application` that consumes it. A service key with an X.509 certificate lets you call the pipeline API.
- **An application in Microsoft Entra ID** with Microsoft Graph application permissions: `Sites.Read.All`, or `Sites.Selected` to limit it to the sites you grant.
- **A BTP destination** to `https://graph.microsoft.com` with `OAuth2ClientCredentials`, or `OAuth2Password` with a technical user. The guide notes that the password variant needs a user without two-factor sign-in.
- **A pipeline**, created by a call to the pipeline API with type `MSSharePoint`, the destination's name, the site and, optionally, a folder.

```mermaid
flowchart LR
  SP[SharePoint site<br/>or folder] -->|Graph, one identity| PL[Pipeline<br/>Document Grounding]
  PL -->|daily| IX[Index]
  U[User] --> J[Joule]
  J -->|informational question| IX
  IX -->|best passages| J
  J --> A[Answer]
```

The SAP Architecture Center calls the retrieval approach retrieval augmented generation for enterprise, and places customer-owned knowledge in Joule's Knowledge Catalog beside SAP's own. SAP Learning's [architecture lesson](https://learning.sap.com/courses/introducing-joule/understanding-joule-s-architecture_a1ea765b-6dc7-4cd9-b741-2a45d9eb9b3a) names the layer Enterprise Knowledge Exploration. [RAG fundamentals](https://erpfde.com/topics/rag-fundamentals/) and [chunking and document preparation](https://erpfde.com/topics/chunking-and-document-preparation/) explain the mechanics underneath.

#### Sources and what each needs

| Source | How it connects, per SAP's pages | What to check |
| --- | --- | --- |
| Microsoft SharePoint | Entra ID application, destination to Graph, pipeline type `MSSharePoint`, optional folder | `Sites.Selected` rather than `Sites.Read.All`; the folder path, which the guide warns can leave an empty pipeline if malformed |
| SAP Build Work Zone | OAuth client in the Work Zone administration console, destination with `OAuth2ClientCredentials`, pipeline type `WorkZone` ([SAP blog](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-sap-build-work-zone-advanced-edition-rag/ba-p/14260070)) | Described for the advanced edition's workspaces; public workspaces only; each sub-workspace enabled separately; [KBA 3755344](https://userapps.support.sap.com/sap/support/knowledge/en/3755344) says PPTX files aren't indexed |
| Google Drive | Named in the feature scope description | The setup page couldn't be opened in this run; confirm the credential and scopes with SAP |
| Joule Studio agents | Control Tower > Document Grounding, with an SAP AI Core destination and an S3 object store destination; the agent gets a *Documents* tool ([SAP tutorial](https://developers.sap.com/tutorials/joulestudio-document-grounding.html), classic edition) | A different route from Joule's own pipelines; the agent's audience decides who may ask |

The generative AI hub in SAP AI Core has its own grounding module for applications you build. [Grounding on SAP data without breaking authorizations](https://erpfde.com/topics/grounding-on-sap-data-with-authorizations/) covers that route, its resource groups and its secrets.

#### Indexing: what becomes text

The setup guide lists HTML, JPEG, JPG, Word, PDF, PNG and TIFF for SharePoint, and says tables and embedded images aren't supported. The feature scope description names DOCX, PDF, PPTX and HTML. The two lists differ, so take the narrower one until SAP confirms your case: a spreadsheet, a table of limits or a scanned form may never become searchable text. The guide states English. It caps grounding at up to 2,000 documents, which you should confirm for your contract.

[KBA 3686888](https://userapps.support.sap.com/sap/support/knowledge/en/3686888) reports a symptom where Joule answers from one SharePoint document instead of several. Its resolution is behind a login. The design lesson holds either way: if two copies of a policy disagree, you can't predict which one answers.

#### Freshness and deletion

The setup guide says SharePoint content is updated once a day, at about the time the pipeline was set up, and that there was no manual refresh. SAP's Work Zone and metadata blogs describe a call that triggers a pipeline run. Plan for daily, and treat a trigger as a help for emergencies, not a design.

Two consequences follow. A changed document answers with the old text until the next run. A deleted document answers until the next run too. The guide also warns that deleting a pipeline clears what it indexed. For a policy that must be right on a date, the owner publishes the new version ahead of the date and states the date in the text, as Calder's credit policy does.

#### Access control: what is known and what isn't

This is the question a review will spend most time on.

- **What SAP states.** The architecture page says a user can't get information or change processes through Joule that they couldn't reach in the application. That sentence is about SAP applications reached as the user.
- **What the grounding pages describe.** Each pipeline reads with one identity. For SharePoint that is an Entra ID application with application permissions, or a technical user. For Work Zone it is an OAuth client.
- **What they don't describe.** A check of each end user's own SharePoint, Drive or workspace permission when Joule answers. Neither the feature scope description nor the setup pages read here mention it.
- **The one documented filter.** For SuccessFactors, the metadata guide tags documents with fields such as company, country or department, and Joule answers only when the tags match the employee's profile. It is configured in SuccessFactors' *Manage Document Grounding* page and, per the guide, needs a new pipeline.

So the conservative rule: **a source feeds Joule only if every Joule user may read every document in it.** If SAP confirms in writing that Joule checks each user's own permission for your source type, record that answer and relax the rule for that source. The lab has a switch for exactly that.

> **Warning** Don't rely on the model to keep a secret. If a confidential passage is retrieved, assume it can appear in an answer, whatever the instructions say. [Prompt injection and tool poisoning](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/) shows why text in documents is untrusted too.

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

You will write Calder's grounding design as a file, review it against thirteen rules, replay eight questions at the times staff ask them, and write a document register your reviewer can sign.

```mermaid
flowchart LR
  I[--init] --> DR[grounding_draft.json]
  I --> RV[grounding_reviewed.json]
  DR --> R[--review<br/>rules G01-G13]
  RV --> R
  DR --> P[--replay<br/>T01-T08]
  RV --> P
  RV --> G[--register]
  G --> M[grounding_register.md]
```

The script is a **course stand-in**. Its retriever counts shared words, and its index is rebuilt once a day at the pipeline's creation time. It models what SAP's pages describe (one reading identity, a daily copy, supported file types, no per-user check unless confirmed), not how SAP's service splits or ranks text.

> **Note** **New words.** **JSON** is a text format for structured data. A **replay** asks saved questions at given times against the index as it stood then. **STALE** means the answer came from a version that has since changed or been deleted; **LEAK** means it came from a document the asker may not read. **Exit code** is the number a program returns: 0 means fine, 2 here means the review found a FAIL.

#### 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/grounding_plan.py`.
2. Paste the code below and save.

```python
"""Review Calder's Joule document grounding design, replay questions against a daily index, write a register.

Usage (run from the orchestrate-course folder):
  python unit23/grounding_plan.py --init                     write the draft and reviewed designs
  python unit23/grounding_plan.py --design FILE --review     check the design against rules G01-G13
  python unit23/grounding_plan.py --design FILE --replay     ask the test questions at their times
  python unit23/grounding_plan.py --design FILE --register   write unit23/grounding_register.md

A course stand-in: the "retriever" counts shared words and the index is rebuilt once a day.
It models what SAP's pages describe (one reading identity per pipeline, daily refresh,
supported file types), not how SAP's service ranks text. Built-in modules only, no randomness.
"""
import argparse
import copy
import json
import re
import sys
from datetime import date, datetime, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent
DRAFT = HERE / "grounding_draft.json"
REVIEWED = HERE / "grounding_reviewed.json"
REGISTER = HERE / "grounding_register.md"

# File types the 2026 feature scope description names, and what the KBA says about Work Zone.
FSD_TYPES = {"DOCX", "PDF", "PPTX", "HTML"}
NOT_INDEXED = {"WorkZone": {"PPTX"}}
STOP = set("a an and are as at be by do does for from how i in is it of on or our the this to what when "
           "which who with we you your per".split())


def at(text):
    return datetime.fromisoformat(text)


USERS = {
    "00100265": {"label": "customer service clerk", "status": "active", "groups": ["all-staff"]},
    "00100266": {"label": "inside sales rep", "status": "active", "groups": ["all-staff"]},
    "00100304": {"label": "credit analyst", "status": "active", "groups": ["all-staff", "credit-team"]},
    "00100196": {"label": "test technician", "status": "active", "groups": ["all-staff"]},
    "00100153": {"label": "maintenance planner", "status": "active", "groups": ["all-staff"]},
    "00100241": {"label": "AP accountant", "status": "active", "groups": ["all-staff"]},
    "00100205": {"label": "rework technician", "status": "active", "groups": ["all-staff"]},
    "00100292": {"label": "integration lead", "status": "active", "groups": ["all-staff"]},
    "00100306": {"label": "HR administrator", "status": "active", "groups": ["all-staff"]},
    "00100314": {"label": "production supervisor", "status": "active", "groups": ["all-staff"]},
    "00100094": {"label": "maintenance technician (left 2026-10-16)", "status": "left", "groups": []},
}

CREDIT_V1 = ["Distributors get open account terms only after a credit check by the credit team.",
             "A new distributor starts with a credit limit of 25,000.00 USD in segment CR01.",
             "Orders above the credit limit are blocked until the credit analyst releases them."]
CREDIT_V2 = ["Distributors get open account terms only after a credit check by the credit team.",
             "From 30 November 2026 a new distributor starts with a credit limit of 20,000.00 USD in segment CR01.",
             "Orders above the credit limit are blocked until the credit analyst releases them."]

DOCS = {
    "DOC-CREDIT-01": {"title": "Credit policy for distributors", "type": "PDF", "audience": "all-staff",
                      "owner": "00100304", "language": "en", "must_be_current": True,
                      "versions": [{"from": "2026-11-01T08:00", "text": CREDIT_V1},
                                   {"from": "2026-11-30T10:00", "text": CREDIT_V2}]},
    "DOC-HR-01": {"title": "Travel and expense policy", "type": "DOCX", "audience": "all-staff",
                  "owner": "00100306", "language": "en",
                  "versions": [{"from": "2026-09-01T08:00",
                                "text": ["Claim expenses within 30 days with a receipt above 25.00 USD.",
                                         "The hotel limit is 220.00 USD per night.",
                                         "The meal limit is 75.00 USD per day."]}]},
    "DOC-EHS-01": {"title": "Test bench coolant refill procedure", "type": "PDF", "audience": "all-staff",
                   "owner": "00100314", "language": "en",
                   "versions": [{"from": "2026-11-20T08:00",
                                 "text": ["Refill the test bench coolant with the drum pump, never by pouring.",
                                          "Wear the face shield at the coolant refill point."]}]},
    "DOC-EHS-02": {"title": "Test bench relief valve lift test", "type": "PDF", "audience": "all-staff",
                   "owner": "00100153", "language": "en",
                   "versions": [{"from": "2026-11-20T08:00",
                                 "text": ["The relief valve on test bench TB-1 is lift tested every 6 months.",
                                          "The lift test needs an issued LOTO permit."]}]},
    "DOC-MT-07": {"title": "Logging rework in the rework area", "type": "DOCX", "audience": "all-staff",
                  "owner": "00100314", "language": "en", "deleted": "2026-11-30T11:00",
                  "versions": [{"from": "2025-03-01T08:00",
                                "text": ["Log rework hours in the rework area on cost center CP11-435."]}]},
}


def reviewed_design():
    return {
        "as_of": "2026-11-28",
        "instance": {"name": "joule-prod", "subaccount": "calder-ai-prod", "region": "us10",
                     "residency": "US", "audience": "all-staff", "work_zone_edition": "standard",
                     "per_user_permissions_confirmed": False},
        "limits": {"documents_per_pipeline": 2000, "secret_warn_days": 30},
        "users": copy.deepcopy(USERS),
        "pipelines": [{
            "id": "P1", "name": "Calder policy library", "type": "MSSharePoint",
            "site": "CalderPolicies", "folder": "/Joule", "audience": "all-staff",
            "auth": "OAuth2ClientCredentials", "graph_permission": "Sites.Selected",
            "technical_user_mfa_off": False, "secret_expires": "2027-11-20",
            "created": "2026-11-28T02:00", "owner": "00100292", "residency": "US",
            "document_count": 5, "metadata_filter": None,
            "documents": copy.deepcopy(DOCS)}],
        "excluded": [
            {"source": "SharePoint site CalderCredit", "reason": "credit-team notes; not every Joule user may read them"},
            {"source": "Google Drive Augsburg Werk", "reason": "CP20 is not on joule-prod until July 2027; EU residency"},
            {"source": "Credit limit matrix (XLSX)", "reason": "spreadsheet; its rule now sits in DOC-CREDIT-01"}],
        "open_questions": [
            {"id": "Q1", "text": "How does Joule apply a repository's per-user permissions when it answers?",
             "owner": "00100292", "due": "2026-12-14"},
            {"id": "Q2", "text": "Which data center holds the grounding index for joule-prod?",
             "owner": "00100292", "due": "2026-12-14"},
            {"id": "Q3", "text": "What document limit per pipeline applies to our contract today?",
             "owner": "00100292", "due": "2026-12-14"},
            {"id": "Q4", "text": "How is document grounding metered under our AI Units contract?",
             "owner": "00100290", "due": "2026-12-14"}],
        "tests": [
            {"id": "T01", "user": "00100265", "at": "2026-11-28T09:00",
             "question": "What does the credit policy say about distributors?", "expect": "ANSWERED", "doc": "DOC-CREDIT-01"},
            {"id": "T02", "user": "00100266", "at": "2026-11-28T09:10",
             "question": "What do the credit review notes say about Hallam?", "expect": "NO SOURCE"},
            {"id": "T03", "user": "00100196", "at": "2026-11-28T09:20",
             "question": "How do I refill the test bench coolant?", "expect": "ANSWERED", "doc": "DOC-EHS-01"},
            {"id": "T04", "user": "00100241", "at": "2026-11-28T09:30",
             "question": "What is the hotel limit per night?", "expect": "ANSWERED", "doc": "DOC-HR-01"},
            {"id": "T05", "user": "00100153", "at": "2026-11-28T09:40",
             "question": "How often is the relief valve lift tested?", "expect": "ANSWERED", "doc": "DOC-EHS-02"},
            {"id": "T06", "user": "00100265", "at": "2026-11-30T14:00",
             "question": "What credit limit does a new distributor start with?", "expect": "STALE", "doc": "DOC-CREDIT-01"},
            {"id": "T07", "user": "00100265", "at": "2026-12-01T09:00",
             "question": "What credit limit does a new distributor start with?", "expect": "ANSWERED", "doc": "DOC-CREDIT-01"},
            {"id": "T08", "user": "00100205", "at": "2026-11-30T15:00",
             "question": "Where do I log rework hours?", "expect": "STALE (DELETED)", "doc": "DOC-MT-07"}],
    }


def draft_design():
    d = reviewed_design()
    docs = copy.deepcopy(DOCS)
    docs["DOC-MT-07"]["owner"] = "00100094"
    docs["DOC-HR-01"]["versions"][0]["table"] = docs["DOC-HR-01"]["versions"][0]["text"][1:]
    docs["DOC-HR-01"]["versions"][0]["text"] = docs["DOC-HR-01"]["versions"][0]["text"][:1]
    old = {"title": "Credit policy for distributors (2024)", "type": "DOCX", "audience": "all-staff",
           "owner": "00100304", "language": "en", "duplicate_of": "DOC-CREDIT-01",
           "versions": [{"from": "2024-02-01T08:00",
                         "text": ["New distributors start with a credit limit of 15,000.00 USD from the credit team."]}]}
    docs = {"DOC-CREDIT-00": old, **docs}  # the old copy sits first in the library
    docs["DOC-CREDIT-02"] = {"title": "Credit limit matrix", "type": "XLSX", "audience": "all-staff",
                             "owner": "00100304", "language": "en",
                             "versions": [{"from": "2026-11-01T08:00", "text": ["Segment CR01 limits by customer class."]}]}
    docs["DOC-CREDIT-03"] = {"title": "Credit review notes on Hallam", "type": "DOCX", "audience": "credit-team",
                             "owner": "00100304", "language": "en",
                             "versions": [{"from": "2026-11-10T08:00",
                                           "text": ["Credit review notes: Hallam paid 19 days late twice; keep the limit at 40,000.00 USD."]}]}
    ehs02 = docs.pop("DOC-EHS-02")
    ehs02["type"] = "PPTX"
    d["pipelines"] = [
        {"id": "P1", "name": "Calder intranet", "type": "MSSharePoint", "site": "CalderIntranet", "folder": "/",
         "audience": "all-staff", "auth": "OAuth2Password", "graph_permission": "Sites.Read.All",
         "technical_user_mfa_off": True, "secret_expires": "2026-12-10", "created": "2026-11-28T02:00",
         "owner": "00100292", "residency": "US", "document_count": 2640,
         "metadata_filter": {"DOC-CREDIT-03": "credit-team"}, "documents": docs},
        {"id": "P2", "name": "Rockford maintenance workspace", "type": "WorkZone", "workspace": "Rockford maintenance",
         "audience": "all-staff", "auth": "OAuth2ClientCredentials", "graph_permission": None,
         "technical_user_mfa_off": False, "secret_expires": "2027-11-20", "created": "2026-11-28T02:00",
         "owner": "00100153", "residency": "US", "document_count": 1, "metadata_filter": None,
         "documents": {"DOC-EHS-02": ehs02}},
        {"id": "P3", "name": "Augsburg Werk drive", "type": "GoogleDrive", "drive": "Augsburg Werk",
         "audience": "all-staff", "auth": "OAuth2ClientCredentials", "graph_permission": None,
         "technical_user_mfa_off": False, "secret_expires": "2027-11-20", "created": "2026-11-28T02:00",
         "owner": "00100292", "residency": "EU", "document_count": 1, "metadata_filter": None,
         "documents": {"DOC-AU-01": {"title": "Schichtuebergabe CNC1", "type": "DOCX", "audience": "all-staff",
                                     "owner": "00100292", "language": "de",
                                     "versions": [{"from": "2026-10-01T08:00",
                                                   "text": ["Schichtuebergabe an CNC1 um 14 Uhr."]}]}}}]
    d["excluded"] = []
    d["open_questions"] = []
    return d


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

def review(d):
    rows = []
    add = lambda rule, level, where, msg: rows.append((rule, level, where, msg))
    as_of = date.fromisoformat(d["as_of"])
    inst, users = d["instance"], d["users"]
    for p in d["pipelines"]:
        pid = p["id"]
        members = {u for u, v in users.items() if p["audience"] in v["groups"]}
        # G01 audience: every document readable by everyone the source answers
        narrow = False
        if p["audience"] != inst["audience"] and not inst.get("per_user_permissions_confirmed"):
            narrow = True
            add("G01", "FAIL", pid, f"source for {p['audience']} on {inst['name']}, which answers {inst['audience']}; "
                                    "per-user permissions not confirmed (Q1)")
        for doc_id, doc in p["documents"].items():
            readers = {u for u, v in users.items() if doc["audience"] in v["groups"]}
            if members - readers:
                narrow = True
                add("G01", "FAIL", f"{pid} {doc_id}", f"audience {doc['audience']} is narrower than the source's {p['audience']}")
        if not narrow:
            add("G01", "OK", pid, f"every document readable by {p['audience']}")
        # G02 file types, G03 tables, G09 language, G13 duplicates
        for doc_id, doc in p["documents"].items():
            t = doc["type"]
            if t in NOT_INDEXED.get(p["type"], set()):
                add("G02", "FAIL", f"{pid} {doc_id}", f"{t} is not indexed from {p['type']} (KBA 3755344)")
            elif t not in FSD_TYPES:
                add("G02", "FAIL", f"{pid} {doc_id}", f"{t} is not a type the feature scope description names")
            if any(v.get("table") for v in doc["versions"]):
                add("G03", "WARN", f"{pid} {doc_id}", "content in tables; SAP's setup guide says tables aren't supported")
            if doc.get("language", "en") != "en":
                add("G09", "WARN", f"{pid} {doc_id}", f"language {doc['language']}; SAP's guide says English only")
            if doc.get("duplicate_of"):
                add("G13", "FAIL", f"{pid} {doc_id}", f"older copy of {doc['duplicate_of']} in the same source")
        if not any(r[0] == "G02" and r[2].startswith(pid) for r in rows):
            add("G02", "OK", pid, "all file types indexable")
        # G04 count
        n, limit = p["document_count"], d["limits"]["documents_per_pipeline"]
        add("G04", "FAIL" if n > limit else "OK", pid, f"{n} document{'s' if n != 1 else ''} against a limit of {limit}")
        # G05 freshness
        for doc_id, doc in p["documents"].items():
            if doc.get("must_be_current"):
                add("G05", "WARN", f"{pid} {doc_id}", "must be current; daily refresh means up to a day behind")
        # G06 owners
        owners = [("pipeline", p["owner"])] + [(k, v["owner"]) for k, v in p["documents"].items()]
        bad = [f"{k} owner {o}" for k, o in owners if users.get(o, {}).get("status") != "active"]
        add("G06", "FAIL" if bad else "OK", pid, "; ".join(bad) if bad else "pipeline and documents owned by active users")
        # G07 credential
        if p["type"] == "MSSharePoint":
            if p["graph_permission"] != "Sites.Selected":
                add("G07", "FAIL", pid, f"{p['graph_permission']} reads every site; use Sites.Selected")
            elif p["auth"] != "OAuth2ClientCredentials" or p["technical_user_mfa_off"]:
                add("G07", "WARN", pid, "a password user; prefer OAuth2ClientCredentials")
            else:
                add("G07", "OK", pid, "OAuth2ClientCredentials with Sites.Selected")
            if p["technical_user_mfa_off"]:
                add("G07", "WARN", pid, "technical user with multi-factor sign-in off")
        # G08 secret expiry
        left = (date.fromisoformat(p["secret_expires"]) - as_of).days
        add("G08", "WARN" if left < d["limits"]["secret_warn_days"] else "OK", pid,
            f"credential expires {p['secret_expires']} ({left} days)")
        # G10 residency
        if p["residency"] != inst["residency"]:
            add("G10", "FAIL", pid, f"residency {p['residency']} feeds {inst['name']} ({inst['residency']})")
        else:
            add("G10", "OK", pid, f"residency {p['residency']}")
        # G11 metadata outside SuccessFactors
        if p.get("metadata_filter") and "sfsf" not in p.get("lob", []):
            add("G11", "FAIL", pid, "relies on metadata to hide documents; SAP's guide offers metadata with SuccessFactors only")
        # G12 Work Zone
        if p["type"] == "WorkZone" and inst["work_zone_edition"] != "advanced":
            add("G12", "FAIL", pid, f"Work Zone grounding described for advanced edition; Calder has {inst['work_zone_edition']}")
    rows.sort(key=lambda r: (r[0], r[2]))
    for rule, level, where, msg in rows:
        print(f"{rule}  {level:<4}  {where:<18} {msg}")
    counts = {k: sum(1 for r in rows if r[1] == k) for k in ("OK", "WARN", "FAIL")}
    print(f"\n{counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return counts["FAIL"] == 0


# ---------- replay ----------

def words(text):
    out = set()
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        out.add(w[:-1] if len(w) > 3 and w.endswith("s") else w)
    return out


def last_refresh(p, t):
    """The pipeline indexes at creation and then once a day at the same time."""
    created = at(p["created"])
    if t < created:
        return None
    return created + timedelta(days=(t - created).days)


def indexed(p, ref):
    """Sentences the index holds after the refresh at time ref."""
    out = []
    for doc_id, doc in p["documents"].items():
        t = doc["type"]
        if t in NOT_INDEXED.get(p["type"], set()) or t not in FSD_TYPES:
            continue
        if doc.get("deleted") and at(doc["deleted"]) <= ref:
            continue
        live = [v for v in doc["versions"] if at(v["from"]) <= ref]
        if live:
            for s in live[-1]["text"]:  # tables are skipped
                out.append((doc_id, live[-1]["from"], s))
    return out


def current_version(doc, t):
    if doc.get("deleted") and at(doc["deleted"]) <= t:
        return None
    return [v for v in doc["versions"] if at(v["from"]) <= t][-1]["from"]


def replay(d):
    users, ok = d["users"], 0
    trims = d["instance"].get("per_user_permissions_confirmed", False)
    for test in d["tests"]:
        t, user = at(test["at"]), users[test["user"]]
        best = (0, None)
        for p in d["pipelines"]:
            ref = last_refresh(p, t)
            if ref is None:
                continue
            for doc_id, ver, s in indexed(p, ref):
                if trims and p["documents"][doc_id]["audience"] not in user["groups"]:
                    continue
                score = len(words(test["question"]) & words(s))
                if score > best[0]:
                    best = (score, (p, doc_id, ver, s))
        if best[0] < 2:
            outcome, doc_id, s = "NO SOURCE", None, ""
        else:
            p, doc_id, ver, s = best[1]
            doc = p["documents"][doc_id]
            now = current_version(doc, t)
            if doc["audience"] not in user["groups"]:
                outcome = "LEAK"
            elif now is None:
                outcome = "STALE (DELETED)"
            elif now != ver:
                outcome = "STALE"
            else:
                outcome = "ANSWERED"
        good = outcome == test["expect"] and (test.get("doc") in (None, doc_id))
        ok += good
        mark = "as expected" if good else f"EXPECTED {test['expect']} {test.get('doc', '')}".rstrip()
        print(f"{test['id']}  {test['at']}  {test['user']}  {outcome:<16} {doc_id or '-':<14} {mark}")
        if s:
            print(f"      \"{s}\"")
    print(f"\n{ok} of {len(d['tests'])} questions behave as expected")
    return ok == len(d["tests"])


# ---------- register ----------

def register(d, path):
    lines = [f"# Document grounding register: {d['instance']['name']} (as of {d['as_of']})", "",
             "| Source | Type | Reads with | Audience | Owner | Refresh | Documents |", "| --- | --- | --- | --- | --- | --- | --- |"]
    for p in d["pipelines"]:
        perm = p["auth"] + (f", {p['graph_permission']}" if p.get("graph_permission") else "")
        lines.append(f"| {p['id']} {p['name']} | {p['type']} | {perm} | {p['audience']} | {p['owner']} | "
                     f"daily from {p['created'][11:]} | {p['document_count']} |")
    lines += ["", "| Document | Title | Type | Audience | Owner |", "| --- | --- | --- | --- | --- |"]
    for p in d["pipelines"]:
        for k, v in p["documents"].items():
            lines.append(f"| {k} | {v['title']} | {v['type']} | {v['audience']} | {v['owner']} |")
    lines += ["", "## Not connected", ""] + [f"- {e['source']}: {e['reason']}" for e in d["excluded"]]
    lines += ["", "## Open with SAP", ""] + [f"- {q['id']} {q['text']} (owner {q['owner']}, due {q['due']})"
                                           for q in d["open_questions"]]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"WROTE {path.name}: {len(d['pipelines'])} source(s), {len(d['excluded'])} not connected, "
          f"{len(d['open_questions'])} open questions")


def load(path):
    p = Path(path)
    if not p.exists():
        sys.exit(f"No file {path}. Run: python unit23/grounding_plan.py --init")
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{path} is not valid JSON: line {e.lineno}, column {e.colno}")


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("--replay", action="store_true")
    ap.add_argument("--register", action="store_true")
    a = ap.parse_args()
    if a.init:
        for path, make in ((DRAFT, draft_design), (REVIEWED, reviewed_design)):
            if path.exists() and not a.force:
                print(f"KEEP {path.name} exists (add --force to overwrite)")
            else:
                path.write_text(json.dumps(make(), indent=2) + "\n", encoding="utf-8")
                print(f"WROTE {path.name}")
        return 0
    if not a.design or not (a.review or a.replay or a.register):
        ap.print_help()
        return 1
    d, code = load(a.design), 0
    if a.review:
        code = 0 if review(d) else 2
    if a.replay:
        if a.review:
            print()
        replay(d)
    if a.register:
        register(d, REGISTER)
    return code


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

#### Step 3: Write the two designs

Run:

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

```text
WROTE grounding_draft.json
WROTE grounding_reviewed.json
```

Open `unit23/grounding_draft.json`. It is the partner's proposal: one pipeline over the whole intranet site (2,640 files, including the credit team's notes, an old copy of the credit policy and a spreadsheet), a Work Zone workspace for maintenance, and Augsburg's Google Drive. `grounding_reviewed.json` is Calder's answer: one curated folder, five documents, three sources left out with reasons, and four questions open with SAP. If you run `--init` again, your files are kept; add `--force` only to start over.

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

```bash
python unit23/grounding_plan.py --design unit23/grounding_draft.json --review
```

```text
G01  FAIL  P1 DOC-CREDIT-03   audience credit-team is narrower than the source's all-staff
G01  OK    P2                 every document readable by all-staff
G01  OK    P3                 every document readable by all-staff
G02  FAIL  P1 DOC-CREDIT-02   XLSX is not a type the feature scope description names
G02  FAIL  P2 DOC-EHS-02      PPTX is not indexed from WorkZone (KBA 3755344)
G02  OK    P3                 all file types indexable
G03  WARN  P1 DOC-HR-01       content in tables; SAP's setup guide says tables aren't supported
G04  FAIL  P1                 2640 documents against a limit of 2000
G04  OK    P2                 1 document against a limit of 2000
G04  OK    P3                 1 document against a limit of 2000
G05  WARN  P1 DOC-CREDIT-01   must be current; daily refresh means up to a day behind
G06  FAIL  P1                 DOC-MT-07 owner 00100094
G06  OK    P2                 pipeline and documents owned by active users
G06  OK    P3                 pipeline and documents owned by active users
G07  FAIL  P1                 Sites.Read.All reads every site; use Sites.Selected
G07  WARN  P1                 technical user with multi-factor sign-in off
G08  WARN  P1                 credential expires 2026-12-10 (12 days)
G08  OK    P2                 credential expires 2027-11-20 (357 days)
G08  OK    P3                 credential expires 2027-11-20 (357 days)
G09  WARN  P3 DOC-AU-01       language de; SAP's guide says English only
G10  OK    P1                 residency US
G10  OK    P2                 residency US
G10  FAIL  P3                 residency EU feeds joule-prod (US)
G11  FAIL  P1                 relies on metadata to hide documents; SAP's guide offers metadata with SuccessFactors only
G12  FAIL  P2                 Work Zone grounding described for advanced edition; Calder has standard
G13  FAIL  P1 DOC-CREDIT-00   older copy of DOC-CREDIT-01 in the same source

11 OK, 5 WARN, 10 FAIL
```

The exit code is 2. Read the FAILs as three groups. **Exposure:** G01, G07 and G11, the credit notes reachable by everyone, a credential that reads every site, and tags standing in for access control. **Content:** G02, G04 and G13, files that never become text, too many documents, and two policies that disagree. **Fit:** G06, G10 and G12, a leaver as owner, EU data feeding a US instance, and a Work Zone feature Calder's edition doesn't have. G02, G03, G09, G11 and G12 restate what SAP's pages say; the others are course rules built on them, with values (2,000 documents, 30 days) you should set for your own contract.

#### Step 5: Replay the questions against the draft

```bash
python unit23/grounding_plan.py --design unit23/grounding_draft.json --replay
```

```text
T01  2026-11-28T09:00  00100265  ANSWERED         DOC-CREDIT-00  EXPECTED ANSWERED DOC-CREDIT-01
      "New distributors start with a credit limit of 15,000.00 USD from the credit team."
T02  2026-11-28T09:10  00100266  LEAK             DOC-CREDIT-03  EXPECTED NO SOURCE
      "Credit review notes: Hallam paid 19 days late twice; keep the limit at 40,000.00 USD."
T03  2026-11-28T09:20  00100196  ANSWERED         DOC-EHS-01     as expected
      "Refill the test bench coolant with the drum pump, never by pouring."
T04  2026-11-28T09:30  00100241  NO SOURCE        -              EXPECTED ANSWERED DOC-HR-01
T05  2026-11-28T09:40  00100153  NO SOURCE        -              EXPECTED ANSWERED DOC-EHS-02
T06  2026-11-30T14:00  00100265  ANSWERED         DOC-CREDIT-00  EXPECTED STALE DOC-CREDIT-01
      "New distributors start with a credit limit of 15,000.00 USD from the credit team."
T07  2026-12-01T09:00  00100265  ANSWERED         DOC-CREDIT-00  EXPECTED ANSWERED DOC-CREDIT-01
      "New distributors start with a credit limit of 15,000.00 USD from the credit team."
T08  2026-11-30T15:00  00100205  STALE (DELETED)  DOC-MT-07      as expected
      "Log rework hours in the rework area on cost center CP11-435."

2 of 8 questions behave as expected
```

> **Note** These results come from made-up Calder documents and a word-counting stand-in. They show the method, not how SAP's service ranks text.

Four failures, four causes. T01, T06 and T07 answer from the 2024 copy, because it sits first in the library and matches the question as well as the real one. T02 is the leak: the rep gets the credit team's note. T04 finds nothing because the hotel limit is in a table. T05 finds nothing because Work Zone doesn't index the PPTX. T08 behaves "as expected" because the test expects the deletion lag: the rework procedure was deleted at 11:00 and still answers at 15:00.

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

```bash
python unit23/grounding_plan.py --design unit23/grounding_reviewed.json --review --replay
```

```text
G01  OK    P1                 every document readable by all-staff
G02  OK    P1                 all file types indexable
G04  OK    P1                 5 documents against a limit of 2000
G05  WARN  P1 DOC-CREDIT-01   must be current; daily refresh means up to a day behind
G06  OK    P1                 pipeline and documents owned by active users
G07  OK    P1                 OAuth2ClientCredentials with Sites.Selected
G08  OK    P1                 credential expires 2027-11-20 (357 days)
G10  OK    P1                 residency US

7 OK, 1 WARN, 0 FAIL

T01  2026-11-28T09:00  00100265  ANSWERED         DOC-CREDIT-01  as expected
      "Distributors get open account terms only after a credit check by the credit team."
T02  2026-11-28T09:10  00100266  NO SOURCE        -              as expected
T03  2026-11-28T09:20  00100196  ANSWERED         DOC-EHS-01     as expected
      "Refill the test bench coolant with the drum pump, never by pouring."
T04  2026-11-28T09:30  00100241  ANSWERED         DOC-HR-01      as expected
      "The hotel limit is 220.00 USD per night."
T05  2026-11-28T09:40  00100153  ANSWERED         DOC-EHS-02     as expected
      "The relief valve on test bench TB-1 is lift tested every 6 months."
T06  2026-11-30T14:00  00100265  STALE            DOC-CREDIT-01  as expected
      "A new distributor starts with a credit limit of 25,000.00 USD in segment CR01."
T07  2026-12-01T09:00  00100265  ANSWERED         DOC-CREDIT-01  as expected
      "From 30 November 2026 a new distributor starts with a credit limit of 20,000.00 USD in segment CR01."
T08  2026-11-30T15:00  00100205  STALE (DELETED)  DOC-MT-07      as expected
      "Log rework hours in the rework area on cost center CP11-435."

8 of 8 questions behave as expected
```

The WARN stays on purpose: the credit policy changed on 30 November at 10:00, and T06 shows Joule giving the old limit at 14:00. The pipeline was created at 02:00, so the change arrives at 02:00 on 1 December (T07). The reviewed design doesn't hide that lag; it records it, and the policy owner now publishes changes the day before they apply.

#### Step 7: Try the one switch SAP could change

The design's `"per_user_permissions_confirmed"` is `false`, because the pages read don't describe a per-user check. Copy the draft and turn it on to see what such a confirmation would change:

1. Copy the file:
   - **Windows (PowerShell):** `Copy-Item unit23/grounding_draft.json unit23/grounding_what_if.json`
   - **macOS / Linux:** `cp unit23/grounding_draft.json unit23/grounding_what_if.json`
2. Open `unit23/grounding_what_if.json` and change `"per_user_permissions_confirmed": false` to `true`.
3. Run the replay:

   ```bash
   python unit23/grounding_plan.py --design unit23/grounding_what_if.json --replay
   ```

T02 now ends `NO SOURCE ... as expected`: with a per-user check, the rep can't reach the credit notes. Everything else stays broken, because duplicates, tables and file types aren't access problems. Delete `grounding_what_if.json` afterwards; it is a what-if, not a design.

#### Step 8: Write the register

```bash
python unit23/grounding_plan.py --design unit23/grounding_reviewed.json --register
```

```text
WROTE grounding_register.md: 1 source(s), 3 not connected, 4 open questions
```

Open `unit23/grounding_register.md`. It lists the source with its credential and refresh time, every document with owner and audience, what was left out and why, and the questions open with SAP. This is the page the document owners and the security reviewer sign.

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

```bash
git add unit23/grounding_plan.py unit23/grounding_draft.json unit23/grounding_reviewed.json unit23/grounding_register.md
git commit -m "Unit 23: Joule document grounding design, replay and register"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `DOCS`, `reviewed_design()`, `draft_design()` | Calder's documents with versions and owners; the reviewed design and the partner's draft with its faults |
| `review()` | Rules G01 to G13 per pipeline and document; any FAIL sets exit code 2 |
| `last_refresh()` | The index runs at the pipeline's creation time and then once a day at the same time |
| `indexed()` | What the index holds after a refresh: supported types only, no tables, no deleted files, the version live at that time |
| `replay()` | Asks each test question at its time, picks the best-matching sentence, and labels it ANSWERED, STALE, STALE (DELETED), LEAK or NO SOURCE |
| `register()` | Writes `grounding_register.md` from the design |

#### 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/grounding_draft.json` | You skipped Step 3, or ran from another folder | Run from `orchestrate-course`: `python unit23/grounding_plan.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 grounding_reviewed.json exists` | Your files are kept on purpose | Add `--force` only to start over |
| `KeyError` with a user number | A test names a user who isn't in `users` | Add the user, or fix the number |
| A question you added ends `NO SOURCE` | Fewer than two of its words match any indexed sentence | Use the document's own words, or check its file type and table content |
| `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 `grounding_plan.py`, not another file |

### The SAP way

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

- **Scope.** Sources SharePoint, Google Drive and SAP Build Work Zone; types DOCX, PDF, PPTX, HTML; automated updates and custom metadata ([feature scope description 3.0.0](https://help.sap.com/doc/0a1c2b2b16f843dca835b44a5db033be/CLOUD/en-US/Joule_FSD.pdf), 5 May 2026). The same document says some features may need a separate subscription.
- **Service and setup.** The Document Grounding service (plan `data-manager`), a Cloud Identity Services instance for API access, a destination, and a pipeline per site or folder ([setup guide](https://community.sap.com/t5/technology-blogs-by-sap/joule-getting-started-with-document-grounding-setup-guide/ba-p/13739501)). Work Zone uses its own OAuth client and pipeline type ([Work Zone guide](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-sap-build-work-zone-advanced-edition-rag/ba-p/14260070)).
- **Metadata.** SuccessFactors offers a *Manage Document Grounding* page that tags SharePoint documents and matches tags to the employee's profile; SAP's guide says Work Zone and ServiceNow are planned ([metadata guide](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-contextualization-aka-metadata-to-your/ba-p/14304077)).
- **Joule Studio.** Classic edition agents use a *Documents* tool on a grounding resource group fed from an S3 object store through SAP AI Core ([SAP tutorial](https://developers.sap.com/tutorials/joulestudio-document-grounding.html)).
- **Licensing.** AI Units for the entitlement (setup guide); metered monthly by records (metadata guide); a flat fee with no prices listed on the [product page](https://www.sap.com/products/artificial-intelligence/document-grounding.html). These don't agree, so take the terms from your contract.
- **Not found in this run.** A per-user permission check at answer time, the index's region, current document limits, and the Google Drive setup page. Ask SAP for each in writing.

### Build vs. SAP

| Need | Joule document grounding | Your own retrieval on BTP | Why |
| --- | --- | --- | --- |
| Answers in Joule, little to run | Yes | No: you build the assistant too | SAP runs indexing, retrieval and the chat |
| Different audiences per document | Keep sources to one audience; SuccessFactors metadata for HR | Yes: filter by the user's groups at query time | [Hybrid search and metadata filtering](https://erpfde.com/topics/hybrid-search-and-metadata-filtering/) shows the filter |
| Refresh faster than daily | Not described | Yes, on your own schedule | Matters for prices, stock or rules that change during the day |
| Tables and spreadsheets | Not supported per SAP's guide | Yes, with your own parsing | Or rewrite the rule as a sentence |
| Retrieval quality you can measure | Through test questions only | Yes, with retrieval metrics | [Evaluating retrieval](https://erpfde.com/topics/evaluating-retrieval/) covers the metrics |
| Data from SAP records | No: use Joule's functions | Yes, as the user | Documents aren't the place for transactional data |

### Architecture view

**Where it sits.** At Calder, `joule-prod` runs in subaccount `calder-ai-prod` (`us10`), with the Document Grounding entitlement in the same subaccount. One pipeline reads the folder `CalderPolicies/Joule` through an Entra ID application limited by `Sites.Selected`. The credit team's site and Augsburg's Drive stay out. The request path is drawn in [How Joule works](https://erpfde.com/topics/how-joule-works/); this is the document side of it.

```mermaid
flowchart LR
  O[Document owners] --> SP[SharePoint<br/>CalderPolicies/Joule]
  SP -->|Entra app<br/>Sites.Selected| DG[Document Grounding<br/>calder-ai-prod]
  DG -->|daily 02:00| IX[Index]
  U[Calder staff] --> IAS[calder-ias] --> J[joule-prod]
  J --> IX
  CR[SharePoint<br/>CalderCredit] -.not connected.-> DG
  AU[Google Drive<br/>Augsburg Werk] -.not connected.-> DG
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Exposure | No document narrower than everyone on Joule | Confidential text answered to anyone |
| Freshness | Changes published a day before they apply | Wrong limits quoted for a day |
| Volume | Under the contract's document limit per pipeline | Partial indexes nobody notices |
| Coverage | Key rules in sentences, in supported types | Joule answers "I don't know" or guesses |
| Ownership | Every document owned by an active person, reviewed yearly | Outdated procedures on safety tasks |
| Credential | Least privilege, rotated before expiry | Pipeline fails silently, index ages |
| Residency | Index in the region the data may live in | A data protection finding |

**Integration and identity.** Users sign in through `calder-ias` as for every Joule request. Documents flow one way, from SharePoint into the index, read by the Entra ID application; no user identity travels with them. Answers to informational questions come from the index. Questions about records go to Joule's functions and reach `S4P` as the user, as in [the connectivity design](https://erpfde.com/topics/btp-connectivity/).

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

- **Context:** Calder wants Joule to answer policy and procedure questions. The partner proposed the whole intranet site, a Work Zone workspace and Augsburg's Drive.
- **Options:** (A) one curated folder readable by all staff; (B) the whole site with metadata tags to hide the credit notes; (C) per-team sources, relying on Joule to check each user's permission.
- **Decision:** A. B leaks the credit notes (T02) and answers from the 2024 copy (T01). C rests on a behavior the pages read don't describe.
- **Consequences:** owners curate the folder and publish changes a day early; the credit team keeps its notes outside Joule; C is reconsidered when SAP answers Q1 in writing; Augsburg waits for the July 2027 rollout and an EU decision.

**What a design review will ask.**

1. Which identity reads each source, and what else can it open?
2. Can every Joule user read every document in every connected source, and who checked?
3. How long after a change or deletion does Joule stop using the old text?
4. Where is the index kept, and how is it metered?
5. Which important answers live in tables, spreadsheets or images?

### Production concerns

- **Security.** Least-privilege credentials (`Sites.Selected`, a dedicated application), no technical user with two-factor sign-in off, and credentials rotated before expiry. The X.509 key from Cloud Identity Services in SAP's guide has a validity you set; track it with your other credentials, as in [services and bindings](https://erpfde.com/topics/btp-services-and-bindings/).
- **SAP authorizations.** Documents bypass SAP's authorization checks entirely. Never put data that SAP would restrict, such as customer credit details, into a connected library.
- **Evaluation.** Keep test questions like T01 to T08, with the expected document. Rerun after each policy change, each new source and each SAP release. [Measuring hallucinations and groundedness](https://erpfde.com/topics/measuring-hallucinations-and-groundedness/) adds checks on the answer itself.
- **Operations.** Watch the pipeline's status after every run. A failed run leaves yesterday's index in place, so failures look like stale answers, not errors.
- **Cost.** Ask how grounding is metered before you size sources. If it is metered by records, a whole-intranet pipeline costs more as well as answering worse.
- **Governance.** A register of sources and documents, owners with review dates, one copy of each policy, and old versions moved out of the connected folder.
- **Clean core.** Nothing here touches the SAP system; grounding is configured on BTP and in the repository.

### Where AI fits

Grounding is how Joule's model gets your facts, and its weak points are not the model's. Retrieval can pick the wrong passage, and the model will write a fluent answer from it. So the controls sit in front of the model: which documents exist in the index, whether they agree, and whether they are current. The model's job is to phrase and cite.

Two AI-specific risks remain. Text in a document can carry instructions meant for the model, so documents from outside Calder (supplier manuals, customer files) need the same suspicion as [any untrusted input](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/). And agents built in Joule Studio may get a *Documents* tool of their own; review each agent's grounding with the same rules, adding who may ask that agent.

### Pitfalls

- **Connecting the whole intranet.** It feels complete and brings every confidential, stale and duplicate file with it.
- **Trusting tags to hide files.** Metadata is described for SuccessFactors content, not as general access control.
- **Two versions of a policy in one source.** You can't predict which one answers.
- **Rules in tables and spreadsheets.** They never become searchable text.
- **Forgetting the day of lag.** Changes and deletions answer for up to a day.
- **A credential that expires quietly.** The pipeline stops, the index ages, and nobody sees an error.
- **No owner per document.** The first wrong answer has nobody to fix it.
- **Assuming the region.** Ask where the index lives before connecting documents with residency rules.

### Exercise

Add the test bench risk assessment for technicians and the credit team's site, find what each breaks, and fix it.

1. Copy the reviewed design:
   - **Windows (PowerShell):** `Copy-Item unit23/grounding_reviewed.json unit23/grounding_exercise.json`
   - **macOS / Linux:** `cp unit23/grounding_reviewed.json unit23/grounding_exercise.json`
2. Open `unit23/grounding_exercise.json`. In pipeline `P1`, change `"document_count": 5` to `6`. In its `"documents"`, find the end of the `"DOC-MT-07"` block, type a comma after its closing `}` and add the safety manager's spreadsheet:

   ```json
   "DOC-EHS-03": {"title": "Test bench risk assessment 000001", "type": "XLSX", "audience": "all-staff",
     "owner": "00100314", "language": "en",
     "versions": [{"from": "2026-11-27T08:00",
       "text": ["The coupling guard on test bench TB-1 must be interlocked before a pressure test."]}]}
   ```

3. In `"pipelines"`, after the closing `}` of `P1`, type a comma and add the credit analyst's request for her team's site:

   ```json
   {"id": "P2", "name": "Credit team site", "type": "MSSharePoint", "site": "CalderCredit", "folder": "/",
    "audience": "credit-team", "auth": "OAuth2ClientCredentials", "graph_permission": "Sites.Selected",
    "technical_user_mfa_off": false, "secret_expires": "2027-11-20", "created": "2026-11-28T02:00",
    "owner": "00100304", "residency": "US", "document_count": 1, "metadata_filter": null,
    "documents": {"DOC-CREDIT-03": {"title": "Credit review notes on Hallam", "type": "DOCX",
      "audience": "credit-team", "owner": "00100304", "language": "en",
      "versions": [{"from": "2026-11-10T08:00",
        "text": ["Credit review notes: Hallam paid 19 days late twice; keep the limit at 40,000.00 USD."]}]}}}
   ```

4. In `"tests"`, after `T08`, type a comma and add:

   ```json
   {"id": "T09", "user": "00100196", "at": "2026-11-28T09:50",
    "question": "Must the coupling guard be interlocked before a pressure test?",
    "expect": "ANSWERED", "doc": "DOC-EHS-03"}
   ```

5. Run the review and the replay:

   ```bash
   python unit23/grounding_plan.py --design unit23/grounding_exercise.json --review --replay
   ```

   The review ends `12 OK, 1 WARN, 2 FAIL`: `G01 FAIL P2` (a source for the credit team on an instance that answers all staff, with Q1 open) and `G02 FAIL P1 DOC-EHS-03` (XLSX). The replay ends `7 of 9`: T02 is now a `LEAK` through P2, and T09 finds `NO SOURCE`.
6. Fix the document: change `DOC-EHS-03`'s `"type"` from `"XLSX"` to `"PDF"` (the safety manager saves the assessment as a PDF with the rule as a sentence).
7. Fix the source: delete the whole `P2` block and the comma before it. The register already lists the credit site under "not connected".
8. Run again and write the register:

   ```bash
   python unit23/grounding_plan.py --design unit23/grounding_exercise.json --review --replay --register
   ```

9. Commit `grounding_exercise.json` and `grounding_register.md`.

**Done when:** the review ends `7 OK, 1 WARN, 0 FAIL`, the replay ends `9 of 9 questions behave as expected` with T09 `ANSWERED DOC-EHS-03`, the register line reads `1 source(s), 3 not connected, 4 open questions`, and you can say in one sentence why P2 fails even though every document in it is readable by its own audience. Keep the register: the Architect capstone (Unit 32) collects it with the security pack.

### Going further

For readers who want SAP's primary material behind the setup.

- [Joule: Getting Started with Document Grounding](https://community.sap.com/t5/technology-blogs-by-sap/joule-getting-started-with-document-grounding-setup-guide/ba-p/13739501): the full SharePoint setup with every call, including the Entra ID application, the Cloud Identity Services key and pipeline deletion. Read it with your Microsoft 365 administrator before choosing between `Sites.Read.All` and `Sites.Selected`.
- [Joule Document Grounding with contextualization](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-contextualization-aka-metadata-to-your/ba-p/14304077): how SuccessFactors maps document tags to employee fields, and why existing pipelines must be recreated. It is the only answer-time filter the pages read describe.
- [Use Document Grounding in Joule Studio](https://developers.sap.com/tutorials/joulestudio-document-grounding.html): the agent route, which feeds a resource group from an object store instead of a Joule pipeline. Useful when one team needs its own documents behind its own agent.
- [Integrating and Extending Joule](https://architecture.learning.sap.com/docs/ref-arch/464deb): where informational questions, the Knowledge Catalog and SAP's Document Grounding services sit among Joule's four capability patterns.

One hard edge: the SAP pages describe how documents get in far better than who may get them out. That asymmetry is why this topic's design is conservative. If SAP documents a per-user check for your source type, the lab's switch shows what you gain, and the rest of the rules still apply.

### Check yourself

1. In SAP's SharePoint setup, whose identity does the pipeline read the site with?
   - A. Each user's own SharePoint identity, passed through to Graph at question time
   - B. The Joule administrator's personal account in Microsoft Entra ID
   - C. One Entra ID application, or a technical user, set in a BTP destination
   - D. The SAP system user that runs Joule's back-end function calls

   Answer: C. SAP's setup guide registers an Entra ID application with Graph application permissions and puts its credential, or a technical user's, in a destination. Everything that identity can open can reach the index.

2. In the lab's draft, why do T01, T06 and T07 answer from DOC-CREDIT-00?
   - A. Because the 2024 policy is newer than the current one
   - B. Because the old copy matches as well and sits first in the library
   - C. Because the current policy is kept in a table and was never indexed
   - D. Because the rep's audience excludes the current credit policy

   Answer: B. Both copies share the question's words, and the stand-in takes the first best match. Rule G13 fails the duplicate because, as SAP's support note on single-document answers suggests, you can't predict which copy answers.

3. Why does T06 end STALE in the reviewed design, and why is that accepted?
   - A. The pipeline failed overnight, and the owner accepted the error
   - B. The question was asked by a user outside the policy's audience
   - C. The credit policy is a PDF, which is refreshed only weekly
   - D. The change came after the 02:00 refresh; owners now publish early

   Answer: D. The index is rebuilt daily at the pipeline's creation time, so a 10:00 change arrives at 02:00 the next day (T07). The design records the lag and moves the control to the owner, who publishes changes a day ahead.

4. Your partner adds the credit team's own site as a second pipeline whose audience is the credit team. What does rule G01 say, and why?
   - A. OK, because every document in it is readable by the credit team
   - B. FAIL, because joule-prod answers all staff and Q1 is still open
   - C. WARN, because the site needs a separate Document Grounding entitlement
   - D. OK, because Sites.Selected limits who can ask about the site

   Answer: B. The pages read don't describe Joule checking each user's permission when it answers. A source narrower than the instance's audience can answer anyone on Joule, which is the leak T02 shows in the exercise.

5. What does the lab's per-user switch change, and what does it leave broken?
   - A. It fixes every draft failure, because they were all access problems
   - B. It fixes the tables, because filtered retrieval reads table cells
   - C. It stops the leak but leaves duplicates, tables and file types broken
   - D. It changes nothing, because the stand-in ignores user groups

   Answer: C. With a per-user check the rep can't reach the credit notes, so T02 passes. The old copy, the table and the PPTX in Work Zone are content problems that no permission check fixes.

6. A Work Zone workspace holds the relief valve procedure as a PPTX. Calder runs Work Zone standard edition. What do you do?
   - A. Connect the workspace, since Work Zone is a named source
   - B. Ask the model to summarize the slides from their titles
   - C. Convert the workspace to private so only technicians see it
   - D. Save it as a PDF in the curated SharePoint folder instead

   Answer: D. SAP's Work Zone guide describes the advanced edition's public workspaces, and KBA 3755344 says PPTX files aren't indexed from Work Zone. A PDF in the curated folder is indexed and fits the existing audience.

7. Why should customer credit details never go into a connected library, even one only the credit team uses today?
   - A. Because SAP's index can't store numbers with decimals
   - B. Because documents bypass the SAP authorization checks on that data
   - C. Because SharePoint can't hold files about named customers
   - D. Because Joule's functions refuse to read customer credit data at all

   Answer: B. Joule's functions reach S4P as the user, so SAP checks who may see credit data. A document copy of the same data is answered from the index with no SAP check, so it belongs in SAP, not in a library.

## Sources

- [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; document grounding uploads documents from Microsoft SharePoint, Google Drive and SAP Build Work Zone; content types DOCX, PDF, PPTX and HTML; automated content updates and ingestion pipelines; custom metadata; no limits, permission model, refresh frequency, languages or licensing named; some features may need a separate subscription
- [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; informational pattern uses customer-owned content by integrating the SAP Document Grounding services; Knowledge Catalog holds SAP knowledge and customer-owned knowledge; retrieval augmented generation for enterprise (RAGe); a user cannot reach information through Joule they couldn't reach in the application
- [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; Enterprise Knowledge Exploration extends grounding to unstructured enterprise content (documents, policies, knowledge sources connected through document grounding); every action traceable to the user and role
- [Joule: Getting Started with Document Grounding, setup guide (SAP Community, Technology Blog Posts by SAP)](https://community.sap.com/t5/technology-blogs-by-sap/joule-getting-started-with-document-grounding-setup-guide/ba-p/13739501): read 2026-11-28; Document Grounding entitlement with plan data-manager, visible with an AI Units licence; Cloud Identity Services instance (plan application) consuming it, X.509 key; destination to Microsoft Graph with OAuth2ClientCredentials or OAuth2Password; Entra application permissions Sites.Read.All or Sites.Selected; pipeline API with type MSSharePoint and an optional folder; up to 2,000 documents; content updated once a day near the time of setup, no manual refresh; tables and embedded images not supported; English
- [Joule Document Grounding with SAP Build Work Zone, advanced edition (SAP Community, Technology Blog Posts by SAP)](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-sap-build-work-zone-advanced-edition-rag/ba-p/14260070): read 2026-11-28; content, knowledge base articles, blogs and wiki pages of workspaces; supported only for public workspaces, each sub-workspace enabled separately; OAuth client in the Work Zone administration console, destination with OAuth2ClientCredentials; pipeline type WorkZone; a trigger call re-indexes; AI Units required
- [Joule Document Grounding with contextualization, aka metadata (SAP Community, Technology Blog Posts by SAP)](https://community.sap.com/t5/technology-blog-posts-by-sap/joule-document-grounding-with-contextualization-aka-metadata-to-your/ba-p/14304077): read 2026-11-28; metadata managed in a user interface only with SAP SuccessFactors; documents tagged with fields such as country and department and matched to the employee's profile at answer time; SharePoint source, Work Zone and ServiceNow planned; a new pipeline is needed for metadata; metered monthly by records
- [Document Grounding (sap.com product page)](https://www.sap.com/products/artificial-intelligence/document-grounding.html): read 2026-11-28; AI feature that adds context to Joule Q&A from documents in SAP and third-party repositories; listed sales metric flat fee with no prices shown; no access-control statement
- [Use Document Grounding in Joule Studio, classic edition (SAP Tutorials)](https://developers.sap.com/tutorials/joulestudio-document-grounding.html): read 2026-11-28; Control Tower > Document Grounding with an SAP AI Core destination and an S3 object store destination; status Pending to Completed; agent tool of type Documents pointing at the grounding resource group
- [KBA 3755344: PPTX files are not indexed from Work Zone advanced via document grounding pipeline (SAP Support, preview)](https://userapps.support.sap.com/sap/support/knowledge/en/3755344): read 2026-11-28 (preview only); pipeline completes but only PDF documents appear when Work Zone advanced edition is the repository
- [KBA 3686888: Joule only takes 1 document into account upon a query related to Document Grounding (SAP Support, preview)](https://userapps.support.sap.com/sap/support/knowledge/en/3686888): read 2026-11-28 (preview only); symptom that Joule answers from one SharePoint document instead of several; resolution not visible
