Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

Project: an HR staffing assistant

Build a skills-to-work matcher on fictional HR data that ranks internal candidates with reasons, logs every step and leaves the decision to a person.

Updated Nov 25, 2026
Foundational layer · 9 min read

The business problem

Calder Pumpworks, the fictional pump maker used throughout this course, loses weeks every time a role or a short assignment needs a person. A technician leaves the Rockford plant. A year-end build needs a second pressure tester for two weeks. A customer's lift stations need field support before Christmas. Each time, a manager asks around, HR searches spreadsheets, and the people who could do the work are found late or not at all.

The skills that matter are often invisible. Rockford's rework technician has replaced seals and impellers on returned pumps all year, but his skills profile in HR is empty. A search on recorded skills ranks him near the bottom. A manager who trusts that list never calls him.

Who feels it: hiring managers waiting for people, HR administrators who do the searching, employees who never hear about work they could do, and the plant, which pays overtime or outside contractors while roles stay open.

Today's numbers must come from your own HR records. This project uses made-up ones: over the last year Calder's ten internal staffing requests took a median of 28.5 days from the request to an offer.

The brief: build an assistant that finds and explains internal candidates for a staffing request, with the controls that hiring AI needs, and that never makes the decision itself. Matching people to work is high-risk under the EU AI Act, so the controls are not an add-on. They are half the project.

What the solution does

A day in the life at Calder after go-live, Wednesday 25 November 2026:

  1. 07:00. The assistant's agent ranks the open request for a maintenance technician. Its list shows five candidates with scores and flags. The rework technician sits fourth at 0%, flagged portfolio empty and skills pending: his work records suggest skills he hasn't confirmed. He also appears under Also consider (data gaps, not skill gaps).
  2. 08:00. The employee sees his suggested skills, from nine confirmed repair jobs, and accepts them. Only he can do that.
  3. 08:15. The maintenance planner, as hiring manager, ranks again. The rework technician is now first at 47%, with a training need: his lockout rating is below what the role needs. The earlier ranking can no longer be used for a decision, because the data changed.
  4. 08:20. The planner opens his explanation: each needed skill, the level he has, and the work records behind it. Only then can she record the offer, with a written reason.
  5. Any time. A candidate can ask why they were or weren't shortlisted and sees only their own explanation. The assistant refuses requests it was never approved for, such as choosing whom to let go.

What the assistant never does: decide, reject anyone, use data such as age, gender or absence, run before workers were told about it, or let anyone delete its log early.

The KPI

Defining success metrics with the business explains how to agree a KPI the business owns.

Time to staff a role Guardrails
Metric Days from a staffing request being opened to the manager's recorded offer Decisions by an agent; offers made without opening the explanation; log integrity
Baseline Median 28.5 days (ten past requests, made-up) Not measured before: decisions lived in email
Target Median at most 10 days 0 agent decisions; every offer explained first; log intact
How it is measured The assistant's own log of decisions, against each request's open date The same log, checked by kpi.py

Why guardrails? A tool that let a manager click "offer" on the top name would cut the days and fail the people. Speed only counts if a person decided, looked at the reasons first and left a record that can't be changed afterwards. The KPI stops at the offer; real staffing also needs acceptance and a start date, which the project leaves to HR's normal process.

Architecture at a glance

flowchart LR
  R[Staffing request<br/>role or assignment] --> G{Ready?<br/>notice given,<br/>approved purpose}
  G -->|no| X[Refused,<br/>logged]
  G -->|yes| M[Match<br/>skills vs needs]
  P[Confirmed skills] --> M
  W[Work records] --> S[Suggested skills]
  S --> E{Employee<br/>accepts?}
  E -->|yes| M
  M --> L[Ranked list<br/>with reasons and flags]
  L --> H[Hiring manager<br/>opens explanation,<br/>decides, writes reason]
  H --> D[(Decision)]
  M -.-> LOG[(Chained log)]
  H -.-> LOG

How the work is split:

  • Matching is plain code. The score is the sum of explained lines: each needed skill, the level the person has, and its source. No model decides who ranks first.
  • Evidence needs the person's consent. Skills suggested from work records count only after the employee accepts them.
  • The agent ranks and explains; people decide. The decision function refuses any user whose ID marks an agent.
  • Everything is logged in a chain where each line includes a fingerprint of the one before, so a changed or deleted line shows.

Where SAP fits. As of 25 November 2026, SuccessFactors covers much of this inside the suite:

  • Opportunity Marketplace recommends assignments, learning and mentors. SAP Learning describes its Intelligent Recommendations as machine learning that needs minimum activity and user volumes before an administrator switches it on (SAP Learning).
  • Personalized Opportunities Recommendation matches employees to opportunities by skills and seniority; SAP's page says AI Units are currently required (SAP).
  • The growth portfolio in Talent Intelligence Hub holds each person's skills; AI-assisted skill recommendations also need AI Units (SAP Learning).

If your company licenses these, start there and use this project to learn what to check in them. SuccessFactors AI and skills graphs covers the suite's AI in full.

Risks and controls

The EU AI Act lists AI used for recruitment and for decisions about promotion, task allocation and similar as high-risk, with those rules applying from 2 December 2027. As a deployer, a company must, among other duties, have competent people oversee the system, keep its logs for at least six months, and inform workers before using it at work (EU AI Act topic). Rockford is in Illinois, which has its own notice rule for AI in employment decisions (US state AI laws topic). This page is not legal advice.

Risk What can go wrong Control in this design
A score becomes a decision A manager or an agent acts on the top name Only a hiring manager or HR records a decision, with a reason, after opening the explanation; agents are refused
Missing data looks like missing skill Empty profiles rank at the bottom Flags for empty and pending profiles; an also consider list; evaluation checks they stay visible
Protected data leaks in An HR extract carries birth dates or absence Loading stops if a forbidden field appears
Use beyond the approved purpose Someone uses it to pick people to let go Only approved purposes run; anything else is refused and logged
Workers not told It runs before notice was given It refuses to rank before the notice dates
Decisions on old data A ranking is used after skills changed A fingerprint of the inputs; a stale ranking can't be decided on
The record is edited Someone changes or deletes a log line Chained log, checked by verify-log; kept at least six months

What to show a stakeholder

A three-minute demo script:

  1. The pain (30 s). Ten past requests, median 28.5 days. The rework technician ranked near the bottom on an empty profile.
  2. The consent (45 s). As the employee, accept the suggested skills. Rank again: first, with a training need.
  3. The decision (60 s). As the agent, try to record the offer: refused. As the planner, try without opening the explanation: refused. Open it, write the reason, record the offer.
  4. The boundary (30 s). Ask it to pick someone to let go: refused, and the refusal is in the log.
  5. The proof (15 s). The evaluation report and the KPI, said plainly to be made-up data.

Questions to ask

  1. Which staffing decisions do we want help with: permanent roles, short assignments, both? Which are out of bounds?
  2. Who has told workers and their representatives, and when, that an AI system helps rank internal candidates?
  3. How complete are our employees' skills profiles, and in which teams are they thin?
  4. Who confirms skills suggested from work records: the employee, the manager, or both?
  5. Who may record a staffing decision, and is the reason written down where an auditor can find it?
  6. How long do we keep the system's logs, and who can delete them?
  7. Does SAP's Opportunity Marketplace or a recommendation feature already cover this in our contract, and at what AI Unit cost?
  8. How would an employee ask why they weren't shortlisted, and who answers?

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1What is the project's KPI, and why does it carry guardrails?

Answer: A. The business wants roles staffed sooner. Offering to the top name would also be faster, so the guardrails require that a person decided, opened the explanation first and left an intact record.

2The rework technician ranks near the bottom because his skills profile is empty. What does the design do?

Answer: C. Missing data is not missing skill. The assistant shows the gap, lists him under "also consider", and counts skills from his work records only after he accepts them himself.

3Under the EU AI Act, when do the high-risk rules for AI used in staffing and promotion apply?

Answer: A. The July 2026 amendment moved the Annex III high-risk rules to 2 December 2027. Employers using such systems are deployers, with duties including competent human oversight, logs kept at least six months and informing workers.

4A manager asks the assistant to choose which technician to let go. What should happen?

Answer: A. The assistant is approved only for filling roles and assignments. A new purpose such as termination changes the risk and needs a new assessment, so the code refuses it and the refusal is logged.

5Which control stops the agent from turning a ranking into a decision?

Answer: A. Instructions in a prompt can be ignored or overridden. The decision function itself refuses agent users, accepts only the hiring manager or HR, and requires a written reason after the explanation was opened.

6Your company licenses SuccessFactors with AI Units. What is the sensible first step?

Answer: C. SAP offers skills-based recommendations in Opportunity Marketplace and related features, which need AI Units. Check them first and use this project's controls as the checklist; as the company using them, you still hold the deployer's duties.

7An employee asks why she wasn't shortlisted. What can she see?

Answer: B. Each person can open their own explanation, built from the same lines that made the score. Other people's explanations stay with the hiring manager and HR.
Deep layer · 60 min read

What you will build

You will build a staffing assistant for Calder's Rockford plant (CP11). It reads a skills library, people's confirmed skills, their work records and open staffing requests. It suggests skills from work records, ranks internal candidates with reasons, and lets only a person decide. Around that core sit the controls: notice before use, an approved purpose, no protected data, consent for suggested skills, a decision gate and a chained log. You will add an API and a small page, prepare a Cloud Foundry deployment, evaluate the ranking against past decisions and compute the KPI from the assistant's own log.

flowchart LR
  S["Stage 1: SAP data<br/>staffing_data.py"] --> C["Stage 2: matching<br/>and controls<br/>staffing.py"]
  C --> A["Stage 3: API<br/>app.py"]
  A --> U["Stage 4: page<br/>served by app.py"]
  A --> D["Stage 5: deploy<br/>manifest.yml"]
  C --> E["Stage 6: evaluation<br/>evaluate.py"]
  C -->|logs/events.jsonl| K["Stage 7: KPI<br/>kpi.py"]
File Stage What it does
staffing_data.py 1 Writes the library, people, skills, work records, bookings, users, notice and requests to data/; past decisions to eval/
staffing.py 2 Suggests skills, ranks, explains, records consent and decisions; the controls and the chained log
test_staffing.py 2 Proves the controls hold
app.py 3, 4 The API and the page, on Python's built-in web server
test_app.py 3 Contract tests for the API
requirements.txt, runtime.txt, manifest.yml, .cfignore 5 Deployment to Cloud Foundry
evaluate.py 6 Scores the ranking on past decisions; checks data gaps, fairness rules and explanations
kpi.py 7 Time to staff a role, with guardrails, from the log

Everything runs on made-up data with Python's built-in modules. No account, key or internet is needed.

Prerequisites. You should have done these published topics, or be ready to look back at them:

Time: 3 to 4 hours over a few sessions. Cost: free.

Stage 1: SAP data

Before you start: complete Set up your computer for this course and Set up for Unit 14. They give you the orchestrate-course folder, its .venv and the Calder suite pack, whose successfactors_people.json holds the same nine Rockford people. This project adds no libraries.

In this stage you write Calder's staffing data to data/ as JSON files. Every later stage reads only these files.

flowchart LR
  A["--sample<br/>made-up Rockford data"] --> F["data/*.json"]
  A --> H["eval/history.json<br/>past decisions"]

What the SAP data looks like

In SuccessFactors the pieces live in different places. The project keeps one file per piece:

What Where it lives in SuccessFactors (as SAP Learning describes it) In this project
Skills library Attribute libraries in Talent Intelligence Hub, holding skills and competencies (SAP Learning) library.json: skill codes and names
A person's skills The growth portfolio, with proficiency levels (SAP Learning) portfolios.json: confirmed levels per personnel number
Evidence of work Completed assignments, performance and 360 reviews, role readiness forms and learning, which write ratings into the growth portfolio work_records.json: confirmed maintenance operation texts (the plant's own evidence, as in Unit 14)
Staffing needs Opportunity Marketplace assignments, usually shorter than 12 months, and internal job postings (SAP Learning) requests.json: needs, must-haves, dates, hiring manager, purpose
People Employee Central employment data people.json: personnel number, job, cost center, shift, hire and leave dates. No names, birth dates, gender or absence

Two facts from SAP's documentation shape the design:

  1. Suggested skills wait for a person. SAP Learning says attributes the AI creates as inferred must be confirmed before employees see them, and a business rule workflow can send employees' rating changes to their manager for approval (SAP Learning). The project's consent step copies that idea: suggested skills count only once the employee accepts them.
  2. Assignments have approvers. In Opportunity Marketplace, assignment owners publish and send offers, and approvers approve applications and offers (SAP Learning). The project's decision gate is the same idea, enforced in code.

The data's "today" is Wednesday 25 November 2026. It holds four requests: SR-0001 the maintenance technician role at work center MECH1 (replacing 00100094, who left on 16 October), SR-0002 a second pressure tester at TEST1 for the year-end build, SR-0003 field support for Brennock's lift stations, and SR-0004, a request to choose someone to let go, which the assistant must refuse.

What you need

  • About 10 minutes. No cost, no account, no internet.

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

  1. Open VS Code, choose File > Open Folder and open orchestrate-course.

  2. Open a terminal: Terminal > New Terminal.

  3. Turn on the virtual environment if the prompt doesn't start with (.venv):

    • Windows (PowerShell):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate

All commands in this project run from the orchestrate-course folder unless a step says otherwise. The python projects/staffing-assistant/... commands are the same in PowerShell and on macOS or Linux.

Step 2: Create the project folder

  1. Create the folder:

    • Windows (PowerShell):

      mkdir projects\staffing-assistant
    • macOS / Linux:

      mkdir -p projects/staffing-assistant
  2. Keep generated files out of Git. Open .gitignore in the course folder, add these lines at the end and save:

    projects/staffing-assistant/data/
    projects/staffing-assistant/state/
    projects/staffing-assistant/logs/

    The script regenerates data/; state/ holds runs, consents and decisions; logs/ holds the chained log. The eval/ folder stays: its report is portfolio material.

Step 3: Save and run the data script

  1. In VS Code's file list, right-click projects/staffing-assistant, choose New File, name it staffing_data.py, paste the code below and save.
"""Stage 1: Calder's Rockford staffing data as files in data/ (and known answers in eval/).

How to run (from your orchestrate-course folder, with .venv turned on):
    python projects/staffing-assistant/staffing_data.py --sample

Built-in Python only, no randomness, no network. Every person is a personnel number with
no name; every value is fictional. Skill codes, levels, rules and request numbers are
course labels, not SAP's. The shapes stand in for SuccessFactors' attributes library,
growth portfolio, Opportunity Marketplace assignments and job requisitions.
"""
import argparse
import hashlib
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
EVAL = HERE / "eval"

META = {"company_code": "CP10", "plant": "CP11", "today": "2026-11-25",
        "rule_version": "staffing-rules 1.0",
        "note": "Fictional Calder Pumpworks data for the Orchestrate course. No real people."}

# The company's skills library (a stand-in for an attributes library). Levels 1 to 3.
LIBRARY = {
    "MECH-REPAIR": "Mechanical repair",
    "PUMP-OVH": "Pump overhaul (seals, impellers)",
    "HYDR": "Hydraulics",
    "LOTO": "Lockout and isolation",
    "VIBR": "Vibration and alignment",
    "PM-CONF": "Maintenance order confirmation in SAP",
    "ELEC": "Industrial electrics",
    "TEST-BENCH": "Pump pressure testing",
    "ASSEMBLY": "Pump assembly",
    "FIELD": "Work at customer sites",
    "PLAN": "Maintenance planning",
    "PURCH": "Purchasing",
}

# People at Rockford: personnel number, job, cost center, shift, hired, left. No names, no
# birth dates, no gender, no nationality, no absence data: the assistant must not see them.
PEOPLE = [
    {"pnr": "00100094", "job": "Maintenance technician", "cost_center": "CP11-450", "shift": 1,
     "hired": "2019-03-04", "left": "2026-10-16"},
    {"pnr": "00100117", "job": "Maintenance technician", "cost_center": "CP11-450", "shift": 1,
     "hired": "2018-06-11", "left": None},
    {"pnr": "00100142", "job": "Maintenance electrician", "cost_center": "CP11-450", "shift": 1,
     "hired": "2021-02-01", "left": None},
    {"pnr": "00100153", "job": "Maintenance planner", "cost_center": "CP11-450", "shift": 1,
     "hired": "2017-09-18", "left": None},
    {"pnr": "00100188", "job": "Assembler", "cost_center": "CP11-410", "shift": 1,
     "hired": "2022-04-25", "left": None},
    {"pnr": "00100196", "job": "Test technician", "cost_center": "CP11-420", "shift": 1,
     "hired": "2020-08-03", "left": None},
    {"pnr": "00100205", "job": "Rework technician", "cost_center": "CP11-435", "shift": 2,
     "hired": "2023-01-09", "left": None},
    {"pnr": "00100211", "job": "Buyer", "cost_center": "CP11-300", "shift": 1,
     "hired": "2024-05-13", "left": None},
    {"pnr": "00100231", "job": "Maintenance technician", "cost_center": "CP11-450", "shift": 2,
     "hired": "2026-10-19", "left": None},
]

# Confirmed skills each person keeps in their own portfolio (a stand-in for a growth portfolio).
PORTFOLIO = {
    "00100117": {"MECH-REPAIR": 3, "PUMP-OVH": 3, "HYDR": 2, "LOTO": 3, "VIBR": 1, "PM-CONF": 3,
                 "FIELD": 2},
    "00100142": {"ELEC": 3, "LOTO": 3, "PM-CONF": 2, "MECH-REPAIR": 1},
    "00100153": {"PLAN": 3, "PM-CONF": 3},
    "00100188": {"ASSEMBLY": 3, "MECH-REPAIR": 2},
    "00100196": {"TEST-BENCH": 3, "HYDR": 2},
    "00100205": {},  # never filled in: an empty portfolio is missing data, not missing skill
    "00100211": {"PURCH": 3},
    "00100231": {"MECH-REPAIR": 2, "LOTO": 3},
}

# Confirmed work: operation texts with the person who did them (course data).
WORK = [
    ("W-001", "00100205", "2026-06-02", "Strip pump and replace mechanical seal"),
    ("W-002", "00100205", "2026-06-16", "Replace impeller and balance rotor"),
    ("W-003", "00100205", "2026-07-07", "Refit flange, torque bolts, replace seal"),
    ("W-004", "00100205", "2026-07-21", "Replace bearing on returned pump"),
    ("W-005", "00100205", "2026-08-04", "Isolate and drain test pump before strip"),
    ("W-006", "00100205", "2026-08-18", "Replace impeller on ES-300, check coupling alignment"),
    ("W-007", "00100205", "2026-09-01", "Replace seal after leak at pressure test"),
    ("W-008", "00100205", "2026-09-15", "Isolate and lock out bench loop, replace bearing"),
    ("W-009", "00100205", "2026-09-22", "Align coupling, measure vibration after rework"),
    ("W-010", "00100196", "2026-07-02", "Pressure test ES-300 at rated flow"),
    ("W-011", "00100196", "2026-08-12", "Change hydraulic oil and filters on test bench"),
    ("W-012", "00100196", "2026-09-09", "Check coupling vibration on test bench"),
    ("W-013", "00100196", "2026-10-07", "Isolate bench and replace pressure transducer"),
    ("W-014", "00100188", "2026-08-20", "Replace bearing on assembly fixture"),
    ("W-015", "00100188", "2026-09-03", "Pressure test ES-200 after assembly"),
    ("W-016", "00100188", "2026-09-17", "Pressure test ES-200, record flow at rated head"),
    ("W-017", "00100188", "2026-10-01", "Isolate fixture air supply before changeover"),
    ("W-018", "00100188", "2026-10-15", "Isolate and lock out press before die change"),
    ("W-019", "00100188", "2026-11-05", "Pressure test ES-300 after seal change"),
    ("W-020", "00100231", "2026-10-27", "Replace bearing on air compressor C-2"),
    ("W-021", "00100231", "2026-11-03", "Align coupling on air compressor C-2"),
    ("W-022", "00100231", "2026-11-10", "Field visit at lift station 4: check coupling alignment"),
    ("W-023", "00100231", "2026-11-17", "Field visit at lift station 7: measure vibration"),
]

# Bookings that make a person unavailable (course data).
BOOKINGS = [
    {"pnr": "00100117", "from": "2026-12-14", "to": "2026-12-23",
     "what": "Year-end shutdown maintenance at CP11"},
    {"pnr": "00100196", "from": "2026-12-07", "to": "2026-12-18",
     "what": "Year-end build: pressure tests at TEST1"},
]

# Who may use the assistant, and for what (course roles).
USERS = {
    "00100153": "hiring manager (maintenance planner)",
    "00100314": "hiring manager (production supervisor)",
    "00100315": "hiring manager (service manager)",
    "00100306": "HR administrator",
    "AGT_STAFFING": "agent: ranks and explains, never decides",
}

# Notice given before first use (the course's stand-in for informing workers and their
# representatives). The assistant refuses to rank before both dates.
NOTICE = {"representatives_informed": "2026-11-09", "workers_informed": "2026-11-16",
          "text": "From 23 November 2026 Rockford uses a staffing assistant that ranks internal "
                  "candidates by skills for open roles and assignments. A manager decides; you "
                  "can ask why you were or weren't shortlisted, and correct your skills."}

REQUESTS = [
    {"id": "SR-0001", "purpose": "fill_role", "title": "Maintenance technician, MECH1, Rockford",
     "job": "Maintenance technician", "manager": "00100153", "opened": "2026-11-23",
     "start": "2026-12-07", "end": None, "percent": 100,
     "needs": {"MECH-REPAIR": 3, "PUMP-OVH": 3, "HYDR": 2, "LOTO": 3, "VIBR": 2, "PM-CONF": 2},
     "must_have": ["LOTO"]},
    {"id": "SR-0002", "purpose": "assignment", "title": "Second pressure tester for the year-end build, TEST1",
     "job": "Test technician", "manager": "00100314", "opened": "2026-11-24",
     "start": "2026-12-07", "end": "2026-12-18", "percent": 50,
     "needs": {"TEST-BENCH": 2, "HYDR": 1, "LOTO": 2}, "must_have": ["TEST-BENCH"]},
    {"id": "SR-0003", "purpose": "assignment", "title": "Field support for Brennock's lift stations",
     "job": None, "manager": "00100315", "opened": "2026-11-25",
     "start": "2026-12-14", "end": "2026-12-23", "percent": 100,
     "needs": {"MECH-REPAIR": 2, "VIBR": 2, "PUMP-OVH": 2, "LOTO": 3, "FIELD": 1},
     "must_have": ["LOTO"]},
    {"id": "SR-0004", "purpose": "reduce_headcount", "title": "Choose one technician to let go in CP11-450",
     "job": None, "manager": "00100153", "opened": "2026-11-25",
     "start": "2027-01-04", "end": None, "percent": 100,
     "needs": {"MECH-REPAIR": 2}, "must_have": []},
]

# Past staffing requests, before the assistant (made-up), with who the manager chose.
# The pool is who was eligible then. Used only by evaluate.py and kpi.py.
HISTORY = [
    {"id": "H-01", "opened": "2025-11-03", "staffed": "2025-11-28", "chosen": "00100117",
     "needs": {"MECH-REPAIR": 3, "PUMP-OVH": 2, "LOTO": 3}, "pool": ["00100117", "00100142", "00100188", "00100205"]},
    {"id": "H-02", "opened": "2025-12-01", "staffed": "2025-12-19", "chosen": "00100196",
     "needs": {"TEST-BENCH": 3, "HYDR": 2}, "pool": ["00100188", "00100196", "00100205"]},
    {"id": "H-03", "opened": "2026-01-12", "staffed": "2026-02-13", "chosen": "00100142",
     "needs": {"ELEC": 3, "LOTO": 2}, "pool": ["00100117", "00100142", "00100231"]},
    {"id": "H-04", "opened": "2026-02-02", "staffed": "2026-03-06", "chosen": "00100205",
     "needs": {"PUMP-OVH": 2, "MECH-REPAIR": 2, "LOTO": 2},
     "pool": ["00100142", "00100188", "00100196", "00100205", "00100211"]},
    {"id": "H-05", "opened": "2026-03-09", "staffed": "2026-03-27", "chosen": "00100188",
     "needs": {"ASSEMBLY": 3, "MECH-REPAIR": 1}, "pool": ["00100188", "00100196", "00100205"]},
    {"id": "H-06", "opened": "2026-04-06", "staffed": "2026-05-15", "chosen": "00100205",
     "needs": {"VIBR": 2, "PUMP-OVH": 3}, "pool": ["00100117", "00100142", "00100188", "00100205"]},
    {"id": "H-07", "opened": "2026-05-04", "staffed": "2026-05-22", "chosen": "00100153",
     "needs": {"PLAN": 3, "PM-CONF": 2}, "pool": ["00100117", "00100153", "00100211"]},
    {"id": "H-08", "opened": "2026-06-01", "staffed": "2026-07-10", "chosen": "00100188",
     "needs": {"TEST-BENCH": 2, "LOTO": 2}, "pool": ["00100142", "00100188", "00100205", "00100211"]},
    {"id": "H-09", "opened": "2026-08-03", "staffed": "2026-08-28", "chosen": "00100211",
     "needs": {"PURCH": 3}, "pool": ["00100153", "00100188", "00100211"]},
    {"id": "H-10", "opened": "2026-09-07", "staffed": "2026-10-16", "chosen": "00100205",
     "needs": {"MECH-REPAIR": 2, "PUMP-OVH": 2, "VIBR": 1},
     "pool": ["00100117", "00100142", "00100188", "00100196", "00100205"]},
]


def write(path: Path, payload) -> str:
    path.parent.mkdir(parents=True, exist_ok=True)
    text = json.dumps(payload, indent=2, sort_keys=True) + "\n"
    path.write_text(text, encoding="utf-8")
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]


def main() -> None:
    ap = argparse.ArgumentParser(description="Write Calder's staffing data to data/.")
    ap.add_argument("--sample", action="store_true", help="write the made-up Calder data (required)")
    args = ap.parse_args()
    if not args.sample:
        ap.error("this project runs on made-up data only: add --sample")
    files = {
        DATA / "meta.json": META,
        DATA / "library.json": LIBRARY,
        DATA / "people.json": PEOPLE,
        DATA / "portfolios.json": PORTFOLIO,
        DATA / "work_records.json": [dict(zip(("id", "pnr", "date", "text"), w)) for w in WORK],
        DATA / "bookings.json": BOOKINGS,
        DATA / "users.json": USERS,
        DATA / "notice.json": NOTICE,
        DATA / "requests.json": REQUESTS,
        EVAL / "history.json": HISTORY,
    }
    for path, payload in files.items():
        print(f"wrote {path.relative_to(HERE).as_posix():<26} {write(path, payload)}")
    print(f"{len(PEOPLE)} people, {len(WORK)} work records, {len(REQUESTS)} requests, "
          f"{len(HISTORY)} past requests. Today is {META['today']}.")


if __name__ == "__main__":
    main()
  1. Run it:

    python projects/staffing-assistant/staffing_data.py --sample

You should see:

wrote data/meta.json             ab45cfd02228
wrote data/library.json          37b373e2ce1c
wrote data/people.json           98e9a69ff69b
wrote data/portfolios.json       d61a8ee9a47f
wrote data/work_records.json     cdd24d0f23c5
wrote data/bookings.json         69dd6adf4b78
wrote data/users.json            c42dd0f233dd
wrote data/notice.json           10a8a91231bf
wrote data/requests.json         fee8ef81cda1
wrote eval/history.json          6e8378ae6df0
9 people, 23 work records, 4 requests, 10 past requests. Today is 2026-11-25.

The twelve-character codes are fingerprints of each file. If yours match, your data is identical to the page's, so every later output should match too.

Step 4 (optional): Look at SAP's side

To see what SuccessFactors APIs look like without a customer system, follow the optional step in Set up for Unit 14: sign in to SAP Business Accelerator Hub, open a SuccessFactors API and try its sandbox if it answers. The project doesn't depend on it.

What the code does

Part What it does
LIBRARY The skills library: twelve codes, levels 1 to 3
PEOPLE Nine Rockford people from the hire-to-retire scenario, with no names or protected data
PORTFOLIO Confirmed skills; 00100205 has none
WORK Confirmed operation texts with an ID (W-001...), the evidence for suggested skills
BOOKINGS Periods when someone is already busy, which matter for assignments
USERS Who may use the assistant: three hiring managers, HR, and the agent
NOTICE The dates workers' representatives and workers were told
REQUESTS The four staffing requests, each with a purpose
HISTORY Ten past requests with who was chosen and how long it took (for Stages 6 and 7)
write() Writes sorted JSON and prints its fingerprint

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 installed or not on the path Go back to Set up your computer; on macOS or Linux try python3
can't open file ... staffing_data.py You're not in orchestrate-course, or the file has another name cd to the course folder; check the file name
error: this project runs on made-up data only: add --sample You left out the flag Add --sample
Different fingerprints The file differs from the page Copy the code again with the copy button

Stage 2: Matching and the controls

Before you start: Stage 1 above. SuccessFactors AI and skills graphs explains the scoring idea; this stage adds the controls a real staffing tool needs.

The "model" here is deliberately plain: a skill counts as far as the request needs it, and the score is the share of needed levels a person has. A language model could read work records more cleverly, but it would make the score harder to explain and to reproduce. In a high-risk use, explainable and repeatable beats clever. The Exercise in SuccessFactors AI and skills graphs is where to try richer evidence.

sequenceDiagram
  participant A as Agent or manager
  participant S as staffing.py
  participant E as Employee
  participant M as Hiring manager
  A->>S: rank SR-0001
  S->>S: notice given? purpose approved?
  S-->>A: RUN with scores, flags, fingerprint
  E->>S: accept my suggested skills
  M->>S: rank again (new RUN)
  M->>S: explain RUN, person
  M->>S: decide RUN, person, reason
  S->>S: person? not agent? latest run? explained?
  S-->>M: decision recorded and logged

What you need

  • About 60 minutes. Free.

Step 1: Save the assistant

  1. Create projects/staffing-assistant/staffing.py, paste the code below and save.
"""Stage 2: the staffing assistant's matching, explanations and controls.

How to run (from your orchestrate-course folder, with .venv turned on):
    python projects/staffing-assistant/staffing.py requests
    python projects/staffing-assistant/staffing.py rank SR-0001 --by 00100153
    python projects/staffing-assistant/staffing.py explain RUN-0001 00100205 --as 00100153
    python projects/staffing-assistant/staffing.py accept 00100205 --by 00100205
    python projects/staffing-assistant/staffing.py decide RUN-0002 00100205 --outcome offer \
        --by 00100153 --reason "..."
    python projects/staffing-assistant/staffing.py verify-log
    python projects/staffing-assistant/staffing.py reset

Built-in Python only, no randomness, sends nothing anywhere. Every value is fictional and
every rule is a course rule, not SAP's and not legal advice.
"""
import argparse
import hashlib
import json
import sys
from datetime import date, datetime, timedelta, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
STATE = HERE / "state" / "state.json"
LOG = HERE / "logs" / "events.jsonl"

AGENT = "AGT_STAFFING"
HR = "00100306"
SHORTLIST = 3
ALLOWED_PURPOSES = {"fill_role", "assignment"}       # the intended purpose, written down
MIN_REASON = 20                                      # characters in a decision's reason
LOG_KEEP_DAYS = 183                                  # keep logs at least six months
# Fields the assistant must never receive. Loading data that holds one stops everything.
FORBIDDEN = {"name", "first_name", "last_name", "date_of_birth", "birth_date", "age", "gender",
             "sex", "nationality", "citizenship", "ethnicity", "religion", "marital_status",
             "disability", "health", "sick_days", "absence_days", "union_member", "photo"}
# Words in an operation text that count as evidence for a skill (course rule).
EVIDENCE_WORDS = {
    "MECH-REPAIR": ["bearing", "flange", "bolts"],
    "PUMP-OVH": ["seal", "impeller"],
    "HYDR": ["hydraulic"],
    "LOTO": ["isolate", "lock out"],
    "VIBR": ["vibration", "coupling", "align"],
    "TEST-BENCH": ["pressure test"],
    "FIELD": ["field visit", "lift station", "customer site"],
}


class Refused(Exception):
    """A control said no. `code` is a short label; the message says why."""

    def __init__(self, code: str, message: str):
        super().__init__(message)
        self.code = code


# ---------- data ----------

def load(data_dir: Path = DATA) -> dict:
    names = ["meta", "library", "people", "portfolios", "work_records", "bookings", "users",
             "notice", "requests"]
    try:
        d = {n: json.loads((data_dir / f"{n}.json").read_text(encoding="utf-8")) for n in names}
    except FileNotFoundError as e:
        raise SystemExit(f"Missing {e.filename}: run staffing_data.py --sample first") from None
    for person in d["people"]:
        bad = FORBIDDEN & {k.lower() for k in person}
        if bad:
            raise Refused("PROTECTED_FIELD", f"people.json holds {sorted(bad)} for "
                          f"{person.get('pnr')}: remove it from the extract before matching")
    d["today"] = date.fromisoformat(d["meta"]["today"])
    return d


def empty_state() -> dict:
    return {"next_run": 1, "runs": {}, "accepted": {}, "decisions": []}


def load_state() -> dict:
    try:
        return json.loads(STATE.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return empty_state()


def save_state(state: dict) -> None:
    STATE.parent.mkdir(parents=True, exist_ok=True)
    STATE.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")


# ---------- the log: append-only, each line chained to the one before ----------

def _digest(event: dict) -> str:
    body = {k: v for k, v in event.items() if k != "hash"}
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode("utf-8")).hexdigest()


def _last_hash() -> str:
    if not LOG.exists():
        return "start"
    lines = LOG.read_text(encoding="utf-8").splitlines()
    return json.loads(lines[-1])["hash"] if lines else "start"


def log_event(kind: str, lab_date: date, **fields) -> dict:
    event = {"kind": kind, "lab_date": lab_date.isoformat(),
             "at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
             "prev": _last_hash(), **fields}
    event["hash"] = _digest(event)
    LOG.parent.mkdir(parents=True, exist_ok=True)
    with LOG.open("a", encoding="utf-8") as f:
        f.write(json.dumps(event, sort_keys=True) + "\n")
    return event


def read_log() -> list:
    if not LOG.exists():
        return []
    return [json.loads(line) for line in LOG.read_text(encoding="utf-8").splitlines() if line]


def verify_log() -> tuple:
    """(ok, events checked, first bad line number or None)."""
    prev = "start"
    events = read_log()
    for i, e in enumerate(events, 1):
        if e.get("prev") != prev or _digest(e) != e.get("hash"):
            return False, len(events), i
        prev = e["hash"]
    return True, len(events), None


def log_refusal(code: str, action: str, by: str, lab_date: date, **fields) -> None:
    """Refused attempts are evidence too: an oversight review reads them."""
    log_event("refused", lab_date, code=code, action=action, by=by, **fields)


def earliest_purge_date(event_date: date) -> date:
    return event_date + timedelta(days=LOG_KEEP_DAYS)


# ---------- skills and matching ----------

def inferred_level(count: int) -> int:
    """Course rule: 2 records give level 1, 3 to 4 give level 2, 5 or more give level 3."""
    return 0 if count < 2 else 1 if count == 2 else 2 if count <= 4 else 3


def infer(pnr: str, d: dict) -> dict:
    """Skills suggested by a person's work records: {skill: {"level", "records"}}."""
    found = {}
    for w in d["work_records"]:
        if w["pnr"] != pnr:
            continue
        low = w["text"].lower()
        for skill, words in EVIDENCE_WORDS.items():
            if any(word in low for word in words):
                found.setdefault(skill, []).append(w["id"])
    return {s: {"level": inferred_level(len(ids)), "records": ids}
            for s, ids in found.items() if inferred_level(len(ids)) > 0}


def skills_of(pnr: str, d: dict, accepted: dict) -> dict:
    """Confirmed skills, plus inferred ones only once the employee accepted them."""
    out = {s: {"level": lvl, "source": "portfolio", "records": []}
           for s, lvl in d["portfolios"].get(pnr, {}).items()}
    if pnr in accepted:
        for s, inf in infer(pnr, d).items():
            if inf["level"] > out.get(s, {}).get("level", 0):
                out[s] = {"level": inf["level"], "source": "inferred, accepted by employee",
                          "records": inf["records"]}
    return out


def overlaps(a_from: str, a_to, b_from: str, b_to) -> bool:
    far = "9999-12-31"
    return a_from <= (b_to or far) and b_from <= (a_to or far)


def eligibility(req: dict, d: dict) -> tuple:
    """Who can be considered, and who is left out by a stated rule (never silently)."""
    keep, out = [], []
    for p in d["people"]:
        pnr = p["pnr"]
        if p["left"] and p["left"] <= req["start"]:
            out.append({"pnr": pnr, "reason": f"left the company on {p['left']}"})
        elif pnr == req["manager"]:
            out.append({"pnr": pnr, "reason": "is the hiring manager for this request"})
        elif req["job"] and p["job"] == req["job"]:
            out.append({"pnr": pnr, "reason": "already holds this job"})
        else:
            # Bookings matter for assignments; a permanent move is planned around them.
            clash = [b for b in d["bookings"] if req["purpose"] == "assignment" and b["pnr"] == pnr
                     and overlaps(b["from"], b["to"], req["start"], req["end"])]
            if clash:
                b = clash[0]
                out.append({"pnr": pnr, "reason": f"booked {b['from']} to {b['to']}: {b['what']}"})
            else:
                keep.append(p)
    return keep, out


def score(req: dict, skills: dict, library: dict) -> dict:
    """One line per needed skill; the score is the sum of the lines' points, nothing else."""
    lines, got, total = [], 0, 0
    for s, need in req["needs"].items():
        have = skills.get(s, {}).get("level", 0)
        points = min(have, need)
        got += points
        total += need
        lines.append({"skill": s, "label": library[s], "needs": need, "has": have,
                      "points": points, "source": skills.get(s, {}).get("source", "none"),
                      "records": skills.get(s, {}).get("records", [])})
    must = [s for s in req["must_have"] if skills.get(s, {}).get("level", 0) < req["needs"][s]]
    return {"lines": lines, "points": got, "of": total, "score": round(100 * got / total),
            "gaps": [l["skill"] for l in lines if l["has"] < l["needs"]], "must_missing": must}


def input_hash(req: dict, d: dict, accepted: dict) -> str:
    """Fingerprint of everything the ranking read. Any change gives a different value."""
    used = {"request": req, "people": d["people"], "portfolios": d["portfolios"],
            "work": d["work_records"], "bookings": d["bookings"], "accepted": sorted(accepted),
            "rules": d["meta"]["rule_version"], "evidence": EVIDENCE_WORDS}
    return hashlib.sha256(json.dumps(used, sort_keys=True).encode("utf-8")).hexdigest()[:16]


def ranking(req: dict, d: dict, accepted: dict) -> dict:
    """Pure function: the same inputs always give the same list (ties broken by number)."""
    keep, out = eligibility(req, d)
    rows = []
    for p in keep:
        sc = score(req, skills_of(p["pnr"], d, accepted), d["library"])
        flags = []
        if not d["portfolios"].get(p["pnr"]) and p["pnr"] not in accepted:
            flags.append("PORTFOLIO_EMPTY")
        pending = set(infer(p["pnr"], d)) & set(req["needs"])
        if pending and p["pnr"] not in accepted:
            flags.append("SKILLS_PENDING")
        if sc["must_missing"]:
            flags.append("TRAINING_FIRST")
        rows.append({"pnr": p["pnr"], "job": p["job"], "score": sc["score"],
                     "points": sc["points"], "of": sc["of"], "flags": flags,
                     "lines": sc["lines"], "must_missing": sc["must_missing"]})
    rows.sort(key=lambda r: (-r["score"], r["pnr"]))
    for i, r in enumerate(rows, 1):
        r["position"] = i
    shortlist = [r["pnr"] for r in rows[:SHORTLIST]]
    also = [r["pnr"] for r in rows[SHORTLIST:] if {"PORTFOLIO_EMPTY", "SKILLS_PENDING"} & set(r["flags"])]
    return {"rows": rows, "excluded": out, "shortlist": shortlist, "also_consider": also}


# ---------- the controls around it ----------

def check_user(user: str, d: dict) -> None:
    if user not in d["users"] and user not in {p["pnr"] for p in d["people"]}:
        raise Refused("UNKNOWN_USER", f"{user} is not a user of the staffing assistant")


def check_ready(req: dict, d: dict) -> None:
    n = d["notice"]
    for key in ("representatives_informed", "workers_informed"):
        if not n.get(key) or date.fromisoformat(n[key]) > d["today"]:
            raise Refused("NO_NOTICE", f"notice not given: {key} is missing or after {d['today']}")
    if req["purpose"] not in ALLOWED_PURPOSES:
        raise Refused("PURPOSE", f"{req['id']} asks for '{req['purpose']}'. The assistant is "
                      f"approved only for {sorted(ALLOWED_PURPOSES)}; anything else needs a new assessment")


def find_request(req_id: str, d: dict) -> dict:
    for r in d["requests"]:
        if r["id"] == req_id:
            return r
    raise Refused("UNKNOWN_REQUEST", f"no staffing request {req_id}")


def rank(req_id: str, by: str, d: dict, state: dict) -> dict:
    check_user(by, d)
    req = find_request(req_id, d)
    if by not in {req["manager"], HR, AGENT}:
        raise Refused("NOT_ALLOWED", f"{by} may not rank {req_id}: only its hiring manager "
                      f"{req['manager']}, HR or the assistant's agent")
    check_ready(req, d)
    result = ranking(req, d, state["accepted"])
    run_id = f"RUN-{state['next_run']:04d}"
    state["next_run"] += 1
    run = {"run": run_id, "request": req_id, "by": by, "lab_date": d["today"].isoformat(),
           "input_hash": input_hash(req, d, state["accepted"]),
           "rules": d["meta"]["rule_version"], **result}
    state["runs"][run_id] = run
    save_state(state)
    log_event("rank", d["today"], run=run_id, request=req_id, by=by, input_hash=run["input_hash"],
              rules=run["rules"], shortlist=run["shortlist"], also_consider=run["also_consider"],
              ranked=[[r["pnr"], r["score"]] for r in run["rows"]], excluded=run["excluded"])
    return run


def get_run(run_id: str, state: dict) -> dict:
    if run_id not in state["runs"]:
        raise Refused("UNKNOWN_RUN", f"no run {run_id}")
    return state["runs"][run_id]


def explain(run_id: str, pnr: str, as_user: str, d: dict, state: dict) -> dict:
    """Why one person scored what they did, from the same lines that made the score."""
    check_user(as_user, d)
    run = get_run(run_id, state)
    req = find_request(run["request"], d)
    if as_user not in {req["manager"], HR, AGENT, pnr}:
        raise Refused("NOT_ALLOWED", f"{as_user} may see only their own explanation")
    row = next((r for r in run["rows"] if r["pnr"] == pnr), None)
    if row is None:
        why = next((x["reason"] for x in run["excluded"] if x["pnr"] == pnr), "not in this run")
        out = {"run": run_id, "pnr": pnr, "considered": False, "reason": why}
    else:
        # The lines stored with the run are exactly what made the score the manager saw.
        stale = input_hash(req, d, state["accepted"]) != run["input_hash"]
        out = {"run": run_id, "pnr": pnr, "considered": True, "position": row["position"],
               "of_candidates": len(run["rows"]), "score": row["score"], "lines": row["lines"],
               "must_missing": row["must_missing"], "flags": row["flags"], "stale": stale,
               "shortlisted": pnr in run["shortlist"]}
        if stale:
            out["note"] = "Data changed since this run; rank again before deciding."
    log_event("explain", d["today"], run=run_id, pnr=pnr, by=as_user)
    return out


def accept(pnr: str, by: str, d: dict, state: dict) -> dict:
    """Only the employee can turn their inferred skills into skills the ranking counts."""
    check_user(by, d)
    if by != pnr:
        raise Refused("NOT_ALLOWED", "only the employee can accept their own inferred skills")
    found = infer(pnr, d)
    if not found:
        raise Refused("NOTHING_TO_ACCEPT", f"{pnr} has no inferred skills")
    state["accepted"][pnr] = d["today"].isoformat()
    save_state(state)
    log_event("accept", d["today"], pnr=pnr, by=by,
              skills={s: v["level"] for s, v in sorted(found.items())})
    return found


def decide(run_id: str, pnr, outcome: str, by: str, reason: str, d: dict, state: dict,
           on: date = None) -> dict:
    """The only function that records a decision about a person. A person makes it."""
    on = on or d["today"]
    check_user(by, d)
    run = get_run(run_id, state)
    req = find_request(run["request"], d)
    if by.startswith("AGT_"):
        raise Refused("AGENT_DECIDES", "an agent can rank and explain; a person decides")
    if by not in {req["manager"], HR}:
        raise Refused("NOT_ALLOWED", f"only {req['manager']} (hiring manager) or HR decide {req['id']}")
    if pnr == by:
        raise Refused("SELF", "nobody decides on their own candidacy")
    if outcome not in {"offer", "no_fit"}:
        raise Refused("OUTCOME", "outcome is offer or no_fit")
    if len((reason or "").strip()) < MIN_REASON:
        raise Refused("NO_REASON", f"write the reason in at least {MIN_REASON} characters")
    latest = max((r for r in state["runs"].values() if r["request"] == req["id"]),
                 key=lambda r: int(r["run"].split("-")[1]))
    if latest["run"] != run_id or input_hash(req, d, state["accepted"]) != run["input_hash"]:
        raise Refused("STALE_RUN", f"{run_id} isn't the latest ranking of current data for "
                      f"{req['id']}: rank again and decide on the new run")
    if any(x["request"] == req["id"] and x["outcome"] == "offer" for x in state["decisions"]):
        raise Refused("ALREADY_DECIDED", f"{req['id']} already has an offer")
    row = None
    if outcome == "offer":
        row = next((r for r in run["rows"] if r["pnr"] == pnr), None)
        if row is None:
            raise Refused("NOT_ELIGIBLE", f"{pnr} wasn't a candidate in {run_id}")
        seen = any(e["kind"] == "explain" and e["run"] == run_id and e["pnr"] == pnr
                   and e["by"] == by for e in read_log())
        if not seen:
            raise Refused("NOT_EXPLAINED", f"open {pnr}'s explanation in {run_id} before deciding")
    decision = {"request": req["id"], "run": run_id, "pnr": pnr, "outcome": outcome, "by": by,
                "reason": reason.strip(), "on": on.isoformat(), "opened": req["opened"],
                "position": row["position"] if row else None,
                "score": row["score"] if row else None,
                "outside_shortlist": bool(row) and pnr not in run["shortlist"]}
    state["decisions"].append(decision)
    save_state(state)
    log_event("decide", on, **decision)
    return decision


# ---------- printing ----------

def print_run(run: dict) -> None:
    print(f"{run['run']}  request {run['request']}  by {run['by']}  on {run['lab_date']}  "
          f"input {run['input_hash']}  ({run['rules']})")
    print("Ranked to help a person decide. Nobody is rejected by this list.\n")
    print("  #  person    job                       score  flags")
    for r in run["rows"]:
        star = "*" if r["pnr"] in run["shortlist"] else " "
        print(f" {star}{r['position']}  {r['pnr']}  {r['job']:<24} {r['score']:>4}%  "
              f"{', '.join(r['flags'])}")
    print(f"\nShortlist (*): {', '.join(run['shortlist']) or 'nobody'}")
    if run["also_consider"]:
        print(f"Also consider (data gaps, not skill gaps): {', '.join(run['also_consider'])}")
    print("Left out by rule:")
    for x in run["excluded"]:
        print(f"  {x['pnr']}  {x['reason']}")


def print_explanation(x: dict) -> None:
    if not x["considered"]:
        print(f"{x['pnr']} was not considered in {x['run']}: {x['reason']}")
        return
    print(f"{x['pnr']} in {x['run']}: position {x['position']} of {x['of_candidates']}, "
          f"score {x['score']}%{'  (shortlisted)' if x['shortlisted'] else ''}")
    for l in x["lines"]:
        mark = "ok " if l["has"] >= l["needs"] else "gap"
        ev = f"  records {', '.join(l['records'])}" if l["records"] else ""
        print(f"  {mark} {l['skill']:<11} needs {l['needs']}, has {l['has']}  "
              f"[{l['source']}]{ev}")
    if x["must_missing"]:
        print(f"  Must-have not met: {', '.join(x['must_missing'])} (training before the first job)")
    if "SKILLS_PENDING" in x["flags"]:
        print("  Skills from work records aren't counted until the employee accepts them.")
    if x.get("note"):
        print(f"  {x['note']}")


def main() -> int:
    ap = argparse.ArgumentParser(description="Calder's staffing assistant (course project).")
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("requests")
    p = sub.add_parser("rank"); p.add_argument("request"); p.add_argument("--by", required=True)
    p = sub.add_parser("explain"); p.add_argument("run"); p.add_argument("pnr")
    p.add_argument("--as", dest="as_user", required=True)
    p = sub.add_parser("accept"); p.add_argument("pnr"); p.add_argument("--by", required=True)
    p = sub.add_parser("decide"); p.add_argument("run"); p.add_argument("pnr", nargs="?")
    p.add_argument("--outcome", default="offer"); p.add_argument("--by", required=True)
    p.add_argument("--reason", default=""); p.add_argument("--on", help="lab date YYYY-MM-DD")
    sub.add_parser("verify-log")
    sub.add_parser("reset")
    args = ap.parse_args()

    if args.cmd == "reset":
        for f in (STATE, LOG):
            if f.exists():
                f.unlink()
        print("State and log cleared.")
        return 0
    try:
        d = load()
        state = load_state()
        if args.cmd == "requests":
            for r in d["requests"]:
                print(f"{r['id']}  {r['purpose']:<16} manager {r['manager']}  opened {r['opened']}  "
                      f"start {r['start']}  {r['title']}")
        elif args.cmd == "rank":
            print_run(rank(args.request, args.by, d, state))
        elif args.cmd == "explain":
            print_explanation(explain(args.run, args.pnr, args.as_user, d, state))
        elif args.cmd == "accept":
            found = accept(args.pnr, args.by, d, state)
            print(f"{args.pnr} accepted: " + ", ".join(f"{s} level {v['level']}"
                                                      for s, v in sorted(found.items())))
        elif args.cmd == "decide":
            on = date.fromisoformat(args.on) if args.on else None
            x = decide(args.run, args.pnr, args.outcome, args.by, args.reason, d, state, on)
            print(f"Decision recorded: {x['request']} {x['outcome']} {x['pnr'] or ''} by {x['by']} "
                  f"on {x['on']} (position {x['position']}, outside shortlist: {x['outside_shortlist']})")
        elif args.cmd == "verify-log":
            ok, n, bad = verify_log()
            print(f"Log {'intact' if ok else 'BROKEN at line ' + str(bad)}: {n} events checked")
            if read_log():
                first = date.fromisoformat(read_log()[0]["lab_date"])
                print(f"Oldest event {first}; keep it at least until {earliest_purge_date(first)}")
            return 0 if ok else 1
    except Refused as e:
        print(f"REFUSED {e.code}: {e}")
        if e.code != "PROTECTED_FIELD":
            log_refusal(e.code, args.cmd, getattr(args, "by", None) or getattr(args, "as_user", None),
                        d["today"], target=getattr(args, "request", None) or getattr(args, "run", None))
        return 2
    return 0


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

Step 2: Rank as the agent

The agent runs the morning ranking for the maintenance technician role:

python projects/staffing-assistant/staffing.py rank SR-0001 --by AGT_STAFFING

You should see (your input fingerprint will match if your data matches):

RUN-0001  request SR-0001  by AGT_STAFFING  on 2026-11-25  input 21f668e2a50d8f0a  (staffing-rules 1.0)
Ranked to help a person decide. Nobody is rejected by this list.

  #  person    job                       score  flags
 *1  00100142  Maintenance electrician    40%  
 *2  00100188  Assembler                  13%  SKILLS_PENDING, TRAINING_FIRST
 *3  00100196  Test technician            13%  TRAINING_FIRST
  4  00100205  Rework technician           0%  PORTFOLIO_EMPTY, SKILLS_PENDING, TRAINING_FIRST
  5  00100211  Buyer                       0%  TRAINING_FIRST

Shortlist (*): 00100142, 00100188, 00100196
Also consider (data gaps, not skill gaps): 00100205
Left out by rule:
  00100094  left the company on 2026-10-16
  00100117  already holds this job
  00100153  is the hiring manager for this request
  00100231  already holds this job

Read it carefully. Nobody is rejected; people left out are listed with the rule that left them out. 00100205 sits at 0% on recorded skills, but is flagged PORTFOLIO_EMPTY and SKILLS_PENDING and listed under Also consider. TRAINING_FIRST means a must-have skill (here lockout, LOTO) is below the needed level: a training need, not a refusal.

Step 3: Ask why, then let the employee accept

  1. Open the rework technician's explanation as the hiring manager:

    python projects/staffing-assistant/staffing.py explain RUN-0001 00100205 --as 00100153
    00100205 in RUN-0001: position 4 of 5, score 0%
      gap HYDR        needs 2, has 0  [none]
      gap LOTO        needs 3, has 0  [none]
      gap MECH-REPAIR needs 3, has 0  [none]
      gap PM-CONF     needs 2, has 0  [none]
      gap PUMP-OVH    needs 3, has 0  [none]
      gap VIBR        needs 2, has 0  [none]
      Must-have not met: LOTO (training before the first job)
      Skills from work records aren't counted until the employee accepts them.
  2. Try to accept his skills for him, as the manager. It is refused:

    python projects/staffing-assistant/staffing.py accept 00100205 --by 00100153
    REFUSED NOT_ALLOWED: only the employee can accept their own inferred skills
  3. Accept as the employee himself:

    python projects/staffing-assistant/staffing.py accept 00100205 --by 00100205
    00100205 accepted: LOTO level 1, MECH-REPAIR level 2, PUMP-OVH level 3, VIBR level 1

Step 4: Rank again and try to decide on the old run

  1. Rank as the hiring manager:

    python projects/staffing-assistant/staffing.py rank SR-0001 --by 00100153

    The top of the list is now:

      #  person    job                       score  flags
     *1  00100205  Rework technician          47%  TRAINING_FIRST
     *2  00100142  Maintenance electrician    40%  
     *3  00100188  Assembler                  13%  SKILLS_PENDING, TRAINING_FIRST
  2. Try to decide on the first run, which was computed before he accepted:

    python projects/staffing-assistant/staffing.py decide RUN-0001 00100142 --by 00100153 --reason "Electrician with lockout experience"
    REFUSED STALE_RUN: RUN-0001 isn't the latest ranking of current data for SR-0001: rank again and decide on the new run

Step 5: Decide as a person, after the explanation

  1. Try to decide as the agent:

    python projects/staffing-assistant/staffing.py decide RUN-0002 00100205 --by AGT_STAFFING --reason "Top of the shortlist with pump overhaul evidence"
    REFUSED AGENT_DECIDES: an agent can rank and explain; a person decides
  2. Open the explanation as the hiring manager:

    python projects/staffing-assistant/staffing.py explain RUN-0002 00100205 --as 00100153
    00100205 in RUN-0002: position 1 of 5, score 47%  (shortlisted)
      gap HYDR        needs 2, has 0  [none]
      gap LOTO        needs 3, has 1  [inferred, accepted by employee]  records W-005, W-008
      gap MECH-REPAIR needs 3, has 2  [inferred, accepted by employee]  records W-003, W-004, W-008
      gap PM-CONF     needs 2, has 0  [none]
      ok  PUMP-OVH    needs 3, has 3  [inferred, accepted by employee]  records W-001, W-002, W-003, W-006, W-007
      gap VIBR        needs 2, has 1  [inferred, accepted by employee]  records W-006, W-009
      Must-have not met: LOTO (training before the first job)

    Each line names its source and the work records behind it. The points add up to the score: 7 of 15 needed levels, 47%.

  3. Record the offer with a reason:

    python projects/staffing-assistant/staffing.py decide RUN-0002 00100205 --by 00100153 --reason "Nine pump repairs on record; LOTO course booked before the first job"
    Decision recorded: SR-0001 offer 00100205 by 00100153 on 2026-11-25 (position 1, outside shortlist: False)

    The manager could have chosen someone further down the list. The decision records that as outside shortlist: True, with the reason, and is allowed: the list informs, the person decides.

Step 6: A candidate's own view, and the boundaries

  1. The electrician asks why he wasn't chosen:

    python projects/staffing-assistant/staffing.py explain RUN-0002 00100142 --as 00100142

    He sees his own six lines. Now ask for the rework technician's:

    python projects/staffing-assistant/staffing.py explain RUN-0002 00100205 --as 00100142
    REFUSED NOT_ALLOWED: 00100142 may see only their own explanation
  2. Staff the other two requests. Each employee accepts their suggested skills, the hiring manager ranks, opens the explanation and decides. --on sets the lab date of the decision, so the KPI in Stage 7 has dates to measure:

    python projects/staffing-assistant/staffing.py accept 00100188 --by 00100188
    python projects/staffing-assistant/staffing.py rank SR-0002 --by 00100314
    python projects/staffing-assistant/staffing.py explain RUN-0003 00100188 --as 00100314
    python projects/staffing-assistant/staffing.py decide RUN-0003 00100188 --by 00100314 --reason "Three pressure tests on ES-200 and ES-300; LOTO refresher before 7 December" --on 2026-11-26
    python projects/staffing-assistant/staffing.py accept 00100231 --by 00100231
    python projects/staffing-assistant/staffing.py rank SR-0003 --by 00100315
    python projects/staffing-assistant/staffing.py explain RUN-0004 00100231 --as 00100315
    python projects/staffing-assistant/staffing.py decide RUN-0004 00100231 --by 00100315 --reason "Two lift station visits in November, full lockout rating" --on 2026-11-27

    In SR-0002, the assembler ranks first at 60% on pressure tests he did on the line. In SR-0003, 00100117 and 00100196 are left out with their bookings named.

  3. Ask for the request the assistant was never approved for:

    python projects/staffing-assistant/staffing.py rank SR-0004 --by 00100153
    REFUSED PURPOSE: SR-0004 asks for 'reduce_headcount'. The assistant is approved only for ['assignment', 'fill_role']; anything else needs a new assessment
  4. Check the log:

    python projects/staffing-assistant/staffing.py verify-log
    Log intact: 20 events checked
    Oldest event 2026-11-25; keep it at least until 2027-05-27

    Twenty events: four rankings, five explanations, three consents, three decisions and five refusals. Refusals are logged because a refused attempt is evidence too. Open logs/events.jsonl in VS Code to read them. Change any character in one line and run verify-log again: it reports the broken line. Then run python projects/staffing-assistant/staffing.py reset and repeat Steps 2 to 6 to get a clean log for Stage 7.

Step 7: Prove the controls with tests

  1. Create projects/staffing-assistant/test_staffing.py, paste the code below and save.
"""Stage 2 tests: the controls hold. Run from projects/staffing-assistant:
    python -m unittest test_staffing -v
Uses a temporary folder for state and log, so your own run is untouched.
"""
import json
import shutil
import tempfile
import unittest
from pathlib import Path

import staffing as st

REASON = "Nine pump repairs on record; LOTO course booked first"


class Controls(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        st.STATE, st.LOG = self.tmp / "state.json", self.tmp / "events.jsonl"
        self.d = st.load()
        self.s = st.empty_state()

    def tearDown(self):
        shutil.rmtree(self.tmp)

    def refused(self, code, fn, *args, **kw):
        with self.assertRaises(st.Refused) as cm:
            fn(*args, **kw)
        self.assertEqual(cm.exception.code, code)

    def ready_run(self):
        """00100205 accepts, the manager ranks SR-0001 and opens the explanation."""
        st.accept("00100205", "00100205", self.d, self.s)
        run = st.rank("SR-0001", "00100153", self.d, self.s)
        st.explain(run["run"], "00100205", "00100153", self.d, self.s)
        return run["run"]

    def test_agent_never_decides(self):
        run = self.ready_run()
        self.refused("AGENT_DECIDES", st.decide, run, "00100205", "offer", st.AGENT, REASON,
                     self.d, self.s)

    def test_only_manager_or_hr_decide(self):
        run = self.ready_run()
        for who in ("00100314", "00100205"):
            self.refused("NOT_ALLOWED", st.decide, run, "00100205", "offer", who, REASON,
                         self.d, self.s)

    def test_reason_required(self):
        run = self.ready_run()
        self.refused("NO_REASON", st.decide, run, "00100205", "offer", "00100153", "fine",
                     self.d, self.s)

    def test_explanation_before_decision(self):
        run = st.rank("SR-0001", "00100153", self.d, self.s)["run"]
        self.refused("NOT_EXPLAINED", st.decide, run, "00100142", "offer", "00100153", REASON,
                     self.d, self.s)

    def test_stale_run_refused(self):
        run = st.rank("SR-0001", "00100153", self.d, self.s)["run"]
        st.explain(run, "00100142", "00100153", self.d, self.s)
        st.accept("00100205", "00100205", self.d, self.s)  # data changed after the run
        self.refused("STALE_RUN", st.decide, run, "00100142", "offer", "00100153", REASON,
                     self.d, self.s)

    def test_one_offer_per_request(self):
        run = self.ready_run()
        st.decide(run, "00100205", "offer", "00100153", REASON, self.d, self.s)
        self.refused("ALREADY_DECIDED", st.decide, run, "00100205", "offer", "00100153", REASON,
                     self.d, self.s)

    def test_purpose_outside_approval_refused(self):
        self.refused("PURPOSE", st.rank, "SR-0004", "00100153", self.d, self.s)

    def test_no_notice_no_ranking(self):
        self.d["notice"]["workers_informed"] = "2026-12-01"
        self.refused("NO_NOTICE", st.rank, "SR-0001", "00100153", self.d, self.s)

    def test_protected_field_stops_loading(self):
        data = self.tmp / "data"
        shutil.copytree(st.DATA, data)
        people = json.loads((data / "people.json").read_text())
        people[0]["date_of_birth"] = "1980-01-01"
        (data / "people.json").write_text(json.dumps(people))
        self.refused("PROTECTED_FIELD", st.load, data)

    def test_only_the_employee_accepts(self):
        self.refused("NOT_ALLOWED", st.accept, "00100205", "00100153", self.d, self.s)

    def test_candidate_sees_only_own_explanation(self):
        run = st.rank("SR-0001", "00100153", self.d, self.s)["run"]
        st.explain(run, "00100205", "00100205", self.d, self.s)
        self.refused("NOT_ALLOWED", st.explain, run, "00100142", "00100205", self.d, self.s)

    def test_explanation_adds_up_and_ranking_repeats(self):
        req = st.find_request("SR-0001", self.d)
        r1 = st.ranking(req, self.d, {})
        self.assertEqual(r1, st.ranking(req, self.d, {}))
        for row in r1["rows"]:
            self.assertEqual(sum(l["points"] for l in row["lines"]), row["points"])

    def test_log_tampering_detected(self):
        self.ready_run()
        self.assertTrue(st.verify_log()[0])
        lines = st.LOG.read_text().splitlines()
        e = json.loads(lines[1]); e["by"] = "00100306"
        lines[1] = json.dumps(e, sort_keys=True)
        st.LOG.write_text("\n".join(lines) + "\n")
        self.assertEqual(st.verify_log()[2], 2)


if __name__ == "__main__":
    unittest.main()
  1. Run the tests from the project folder:

    • Windows (PowerShell):

      cd projects\staffing-assistant
      python -m unittest test_staffing -v
      cd ..\..
    • macOS / Linux:

      cd projects/staffing-assistant
      python -m unittest test_staffing -v
      cd ../..

    The last lines should read:

    Ran 13 tests in 0.020s
    
    OK

    The time varies. The tests use a temporary folder, so your own state and log are untouched.

What the code does

Part What it does
FORBIDDEN, load() Stops loading if a person record carries a field such as birth date, gender or absence days
log_event(), verify_log() Appends events with the previous line's fingerprint; checks the chain
EVIDENCE_WORDS, infer() Suggests skills from work records by course word rules; 2 records give level 1, 3 to 4 level 2, 5 or more level 3
skills_of() Confirmed skills, plus suggested ones only after the employee accepted
eligibility() Leaves people out only by stated rules (left, hiring manager, already in the job, booked for an assignment), each with its reason
score() One line per needed skill; the score is the sum of the lines
ranking() Pure function: same input, same list; ties broken by personnel number; flags data gaps
input_hash() Fingerprint of everything a ranking read
check_ready() Refuses before the notice dates or for an unapproved purpose
rank(), explain(), accept() The actions, each checking who is asking, each logged
decide() The only way to record a decision: a person, not an agent, the right role, a reason, the latest run on current data, the explanation opened first, one offer per request

If something goes wrong

What you see What it means What to do
Missing ...: run staffing_data.py --sample first data/ doesn't exist Run Stage 1
REFUSED UNKNOWN_RUN The run number doesn't exist, often after reset Rank again and use the new number
REFUSED STALE_RUN on a run you just made Someone accepted skills or the data changed after it Rank again
REFUSED NOT_EXPLAINED The decider hasn't opened that person's explanation in that run Run explain with --as the decider
REFUSED ALREADY_DECIDED The request already has an offer Expected; reset to start over
ModuleNotFoundError: No module named 'staffing' in the tests The tests ran from the wrong folder cd into projects/staffing-assistant first

Stage 3: API

Before you start: Stages 1 and 2 above. Building an AI API explains endpoints and contract tests; this project uses Python's built-in web server to stay free of libraries.

The API exposes the same functions, so the controls can't be skipped by calling it. Each request names its user in an X-Lab-User header.

Method and path What it does Refusals
GET /health Answers {"ok": true} None
GET /api/requests Lists staffing requests 401 without a user, 403 for an unknown user
POST /api/rank {"request"} Ranks and returns the run 403 wrong user, 409 notice or purpose
GET /api/runs/{run}/explain/{pnr} One person's explanation 403 if it isn't yours and you aren't the manager or HR
POST /api/accept {"pnr"} The employee accepts suggested skills 403 for anyone else
POST /api/decide {"run","pnr","reason"} Records an offer 403 agent or wrong role, 409 stale, unexplained or already decided
GET /api/verify-log Checks the chain None

What you need

  • About 30 minutes. Free.

Step 1: Save the API

  1. Create projects/staffing-assistant/app.py, paste the code below and save.
"""Stages 3 and 4: the staffing assistant's API and a small page, on Python's built-in server.

How to run (from your orchestrate-course folder, with .venv turned on):
    python projects/staffing-assistant/app.py
Then open http://127.0.0.1:8792 . Stop with Ctrl+C.

The lab identity is a header, X-Lab-User, that the page sets from a picker. That is a course
stand-in with no sign-on: never put this app on a public URL with real data.
"""
import json
import os
import re
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import staffing as st

LOCK = threading.Lock()
FORBIDDEN_CODES = {"NOT_ALLOWED", "AGENT_DECIDES", "SELF", "UNKNOWN_USER"}

PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Calder staffing assistant (course lab)</title>
<style>
body{font:15px/1.45 system-ui,sans-serif;margin:16px;max-width:980px;color:#1d2433;background:#fff}
h1{font-size:20px}table{border-collapse:collapse;width:100%;margin:8px 0;display:block;overflow-x:auto}
td,th{border-bottom:1px solid #d9dde5;padding:4px 6px;text-align:left;vertical-align:top}
button{margin:2px}.flag{font-size:12px;background:#eef1f6;border-radius:4px;padding:1px 5px}
.msg{padding:8px;margin:8px 0;border-radius:6px;background:#f3f6fb}.err{background:#fdecec}
pre{white-space:pre-wrap;background:#f7f8fa;padding:8px;border-radius:6px}
</style></head><body>
<h1>Calder staffing assistant <small>(fictional data, course lab)</small></h1>
<p>Acting as <select id="user">
<option value="00100153">00100153 hiring manager (maintenance planner)</option>
<option value="00100314">00100314 hiring manager (production supervisor)</option>
<option value="00100315">00100315 hiring manager (service manager)</option>
<option value="00100306">00100306 HR administrator</option>
<option value="00100205">00100205 employee (rework technician)</option>
<option value="00100188">00100188 employee (assembler)</option>
<option value="00100231">00100231 employee (maintenance technician)</option>
<option value="AGT_STAFFING">AGT_STAFFING agent</option></select>
<button onclick="acceptMine()">Accept my suggested skills</button></p>
<div id="msg"></div><h2>Staffing requests</h2><table id="reqs"></table>
<div id="run"></div><div id="explain"></div>
<script>
const $=id=>document.getElementById(id);
addEventListener("unhandledrejection",e=>e.preventDefault()); // refusals are shown in the message box
function show(t,err){$("msg").innerHTML='<div class="msg'+(err?' err':'')+'">'+t+'</div>'}
async function call(path,body){
  const r=await fetch(path,{method:body?"POST":"GET",headers:{"X-Lab-User":$("user").value,
    "Content-Type":"application/json"},body:body?JSON.stringify(body):undefined});
  const j=await r.json(); if(!r.ok){show((j.code||r.status)+": "+j.error,true);throw j} return j}
async function load(){const j=await call("/api/requests");$("reqs").innerHTML=
  "<tr><th>Request</th><th>Purpose</th><th>Manager</th><th>Start</th><th>Title</th><th></th></tr>"+
  j.requests.map(r=>`<tr><td>${r.id}</td><td>${r.purpose}</td><td>${r.manager}</td><td>${r.start}</td>
  <td>${r.title}</td><td><button onclick="rank('${r.id}')">Rank</button></td></tr>`).join("")}
async function rank(id){const r=await call("/api/rank",{request:id});show(r.run+" ranked "+id);
  $("explain").innerHTML="";$("run").innerHTML=`<h2>${r.run} for ${r.request}</h2>
  <p>Ranked to help a person decide. Nobody is rejected by this list.</p><table>
  <tr><th>#</th><th>Person</th><th>Job</th><th>Score</th><th>Flags</th><th></th></tr>`+
  r.rows.map(x=>`<tr><td>${r.shortlist.includes(x.pnr)?"*":""}${x.position}</td><td>${x.pnr}</td>
  <td>${x.job}</td><td>${x.score}%</td><td>${x.flags.map(f=>'<span class="flag">'+f+'</span>').join(" ")}</td>
  <td><button onclick="explain('${r.run}','${x.pnr}')">Why?</button></td></tr>`).join("")+
  "</table><p>Left out by rule: "+r.excluded.map(x=>x.pnr+" ("+x.reason+")").join("; ")+"</p>"}
async function explain(run,pnr){const x=await call(`/api/runs/${run}/explain/${pnr}`);
  $("explain").innerHTML=`<h3>${pnr} in ${run}: ${x.score}% (position ${x.position})</h3><pre>`+
  x.lines.map(l=>`${l.has>=l.needs?"ok ":"gap"} ${l.skill.padEnd(11)} needs ${l.needs}, has ${l.has} [${l.source}] ${l.records.join(", ")}`).join("\\n")+
  (x.must_missing.length?"\\nMust-have not met: "+x.must_missing.join(", "):"")+(x.note?"\\n"+x.note:"")+
  `</pre><p>Decision on ${pnr}: <input id="reason" style="width:100%;max-width:520px" placeholder="Reason (at least 20 characters)">
  <button onclick="decide('${run}','${pnr}')">Record offer</button></p>`}
async function decide(run,pnr){const x=await call("/api/decide",{run,pnr,outcome:"offer",
  reason:$("reason").value});show("Offer recorded for "+x.pnr+" by "+x.by+" on "+x.on)}
async function acceptMine(){const x=await call("/api/accept",{pnr:$("user").value});
  show("Accepted: "+Object.keys(x.accepted).join(", "))}
load();
</script></body></html>"""


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):  # keep the terminal quiet; the assistant has its own log
        pass

    def send(self, status: int, payload, ctype="application/json") -> None:
        body = payload.encode("utf-8") if isinstance(payload, str) else json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def body(self) -> dict:
        n = int(self.headers.get("Content-Length") or 0)
        return json.loads(self.rfile.read(n) or b"{}") if n else {}

    def handle_any(self, method: str) -> None:
        path = self.path.split("?")[0]
        if method == "GET" and path == "/":
            return self.send(200, PAGE, "text/html; charset=utf-8")
        if method == "GET" and path == "/health":
            return self.send(200, {"ok": True})
        user = self.headers.get("X-Lab-User")
        if not user:
            return self.send(401, {"code": "NO_USER", "error": "send the X-Lab-User header"})
        with LOCK:
            d, state = st.load(), st.load_state()
            try:
                if method == "GET" and path == "/api/requests":
                    st.check_user(user, d)
                    return self.send(200, {"requests": d["requests"], "today": d["meta"]["today"]})
                if method == "POST" and path == "/api/rank":
                    return self.send(200, st.rank(self.body().get("request", ""), user, d, state))
                m = re.fullmatch(r"/api/runs/(RUN-\d{4})/explain/(\d{8})", path)
                if method == "GET" and m:
                    return self.send(200, st.explain(m[1], m[2], user, d, state))
                if method == "POST" and path == "/api/accept":
                    pnr = self.body().get("pnr", "")
                    found = st.accept(pnr, user, d, state)
                    return self.send(200, {"pnr": pnr, "accepted": found})
                if method == "POST" and path == "/api/decide":
                    b = self.body()
                    return self.send(200, st.decide(b.get("run", ""), b.get("pnr"),
                                                     b.get("outcome", "offer"), user,
                                                     b.get("reason", ""), d, state))
                if method == "GET" and path == "/api/verify-log":
                    ok, n, bad = st.verify_log()
                    return self.send(200, {"intact": ok, "events": n, "first_bad_line": bad})
                return self.send(404, {"code": "NOT_FOUND", "error": f"no route {method} {path}"})
            except st.Refused as e:
                st.log_refusal(e.code, f"{method} {path}", user, d["today"])
                return self.send(403 if e.code in FORBIDDEN_CODES else 409,
                                 {"code": e.code, "error": str(e)})

    def do_GET(self):
        self.handle_any("GET")

    def do_POST(self):
        self.handle_any("POST")


def make_server(port: int, host: str) -> ThreadingHTTPServer:
    return ThreadingHTTPServer((host, port), Handler)


def main() -> None:
    port = int(os.environ.get("PORT", "8792"))
    host = "0.0.0.0" if "PORT" in os.environ else "127.0.0.1"  # all interfaces only in the cloud
    server = make_server(port, host)
    print(f"Staffing assistant on http://127.0.0.1:{port}  (Ctrl+C to stop)")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()


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

Step 2: Save and run the contract tests

  1. Create projects/staffing-assistant/test_app.py, paste the code below and save.
"""Stage 3 contract tests for the API. Run from projects/staffing-assistant:
    python -m unittest test_app -v
Starts the app on a free local port with a temporary state and log.
"""
import json
import shutil
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
from pathlib import Path

import app
import staffing as st


class Api(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.tmp = Path(tempfile.mkdtemp())
        st.STATE, st.LOG = cls.tmp / "state.json", cls.tmp / "events.jsonl"
        cls.server = app.make_server(0, "127.0.0.1")
        cls.base = f"http://127.0.0.1:{cls.server.server_address[1]}"
        threading.Thread(target=cls.server.serve_forever, daemon=True).start()

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()
        cls.server.server_close()
        shutil.rmtree(cls.tmp)

    def call(self, path, user=None, body=None):
        headers = {"Content-Type": "application/json"}
        if user:
            headers["X-Lab-User"] = user
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(self.base + path, data=data, headers=headers,
                                     method="POST" if body is not None else "GET")
        try:
            with urllib.request.urlopen(req) as r:
                return r.status, json.loads(r.read())
        except urllib.error.HTTPError as e:
            return e.code, json.loads(e.read())

    def test_a_flow(self):
        self.assertEqual(self.call("/health")[0], 200)
        self.assertEqual(self.call("/api/requests")[0], 401)
        status, out = self.call("/api/accept", "00100205", {"pnr": "00100205"})
        self.assertEqual(status, 200)
        status, run = self.call("/api/rank", "00100153", {"request": "SR-0001"})
        self.assertEqual((status, run["rows"][0]["pnr"]), (200, "00100205"))
        status, out = self.call("/api/decide", "AGT_STAFFING",
                                {"run": run["run"], "pnr": "00100205", "reason": "x" * 30})
        self.assertEqual((status, out["code"]), (403, "AGENT_DECIDES"))
        status, out = self.call("/api/decide", "00100153",
                                {"run": run["run"], "pnr": "00100205", "reason": "x" * 30})
        self.assertEqual((status, out["code"]), (409, "NOT_EXPLAINED"))
        status, x = self.call(f"/api/runs/{run['run']}/explain/00100205", "00100153")
        self.assertEqual(sum(l["points"] for l in x["lines"]), run["rows"][0]["points"])
        status, out = self.call("/api/decide", "00100153",
                                {"run": run["run"], "pnr": "00100205",
                                 "reason": "Nine pump repairs on record; LOTO course first"})
        self.assertEqual((status, out["outcome"]), (200, "offer"))
        self.assertTrue(self.call("/api/verify-log", "00100306")[1]["intact"])

    def test_b_refusals(self):
        status, out = self.call("/api/rank", "00100153", {"request": "SR-0004"})
        self.assertEqual((status, out["code"]), (409, "PURPOSE"))
        status, out = self.call("/api/rank", "00100205", {"request": "SR-0001"})
        self.assertEqual((status, out["code"]), (403, "NOT_ALLOWED"))
        status, out = self.call("/api/requests", "99999999")
        self.assertEqual((status, out["code"]), (403, "UNKNOWN_USER"))


if __name__ == "__main__":
    unittest.main()
  1. From the project folder, run both test files:

    • Windows (PowerShell):

      cd projects\staffing-assistant
      python -m unittest test_app test_staffing
      cd ..\..
    • macOS / Linux:

      cd projects/staffing-assistant
      python -m unittest test_app test_staffing
      cd ../..
    Ran 15 tests in 0.574s
    
    OK

Step 3: Start the API and call it

  1. Start it:

    python projects/staffing-assistant/app.py
    Staffing assistant on http://127.0.0.1:8792  (Ctrl+C to stop)
  2. In a second terminal (with .venv turned on), list the requests:

    • Windows (PowerShell):

      Invoke-RestMethod http://127.0.0.1:8792/api/requests -Headers @{"X-Lab-User"="00100306"}
    • macOS / Linux:

      curl -s -H "X-Lab-User: 00100306" http://127.0.0.1:8792/api/requests

    You should get the four requests as JSON. Leave the API running for Stage 4.

What the code does

Part What it does
Handler.handle_any() Routes each request to the same functions the command line uses, inside a lock so two requests can't write at once
FORBIDDEN_CODES Maps permission refusals to 403 and other refusals to 409
st.log_refusal() Logs refused API calls too
PAGE The small web page for Stage 4
main() Listens on 127.0.0.1:8792; on all interfaces only when the cloud sets PORT

If something goes wrong

What you see What it means What to do
OSError: [Errno 98] Address already in use (or 10048 on Windows) Another program uses port 8792 Stop the other API, or start with PORT=8793 (PowerShell: $env:PORT="8793")
curl: (7) Failed to connect The API isn't running Start it in the first terminal
A proxy or firewall blocks 127.0.0.1 Company security software Ask IT to allow local connections, or run the tests only

Stage 4: UI

Before you start: Stage 3 with the API running. You may want python projects/staffing-assistant/staffing.py reset first, for a clean run.

Step 1: Work a request as the employee and the manager

  1. Open http://127.0.0.1:8792 in your browser.
  2. Pick 00100205 employee (rework technician) under Acting as and choose Accept my suggested skills.
  3. Pick 00100153 hiring manager (maintenance planner), then Rank on SR-0001. The rework technician is first at 47%.
  4. Choose Why? on his row. Read the lines and their work records.
  5. Type a reason of at least 20 characters and choose Record offer. The message says the offer was recorded.

Step 2: Try what isn't allowed

  1. Pick AGT_STAFFING agent and choose Rank on SR-0004: the purpose refusal appears in red.
  2. Pick 00100205 employee, rank SR-0001: NOT_ALLOWED, because employees don't rank.

What the page does

Part What it does
Acting as picker Sets the X-Lab-User header on every call
Requests table GET /api/requests, one Rank button per request
Run table The ranking, flags, shortlist marks and the people left out by rule
Why? and Record offer The explanation, then the decision form under it, so a decision always follows an explanation

If something goes wrong

What you see What it means What to do
The page is blank The API stopped, or you opened the wrong port Restart app.py; open http://127.0.0.1:8792
STALE_RUN when recording Someone accepted skills after you ranked Rank again, then Why? and record
ALREADY_DECIDED The request has an offer Run reset in a terminal, stop and start the API

Stage 5: Deployment

Before you start: Deploying AI apps on SAP BTP shows the Cloud Foundry routine on the free BTP trial, and Set up for Unit 5 installs the cf command.

Two decisions shape the deployment:

  1. The demo deploys only made-up data. The start command writes data/ from the script, so no file with people in it is uploaded.
  2. The demo has no sign-on, so it must not stay public. Anyone with the URL can pick a user. Stop the app after the demo.

What you need

  • About 20 minutes for Steps 1 and 2, on your computer. Free.
  • For Step 3: your SAP BTP trial and the cf command.

Step 1: Create the deployment files

  1. In projects/staffing-assistant, create requirements.txt with this one line. The app needs no library, but the Python buildpack looks for the file:

    # no libraries needed: built-in Python only
  2. Create runtime.txt:

    python-3.13.x
  3. Create manifest.yml (spaces, not tabs):

    ---
    applications:
    - name: staffing-assistant
      path: .
      memory: 128M
      instances: 1
      random-route: true
      buildpacks:
      - python_buildpack
      command: python staffing_data.py --sample > /dev/null && python app.py
      health-check-type: http
      health-check-http-endpoint: /health
  4. Create .cfignore (with the dot):

    .env
    .venv/
    __pycache__/
    data/
    state/
    logs/
    eval/

Step 2: Run it the way the cloud will

Cloud Foundry sets PORT and runs the manifest's command. Try the same locally:

  • Windows (PowerShell):

    cd projects\staffing-assistant
    python staffing_data.py --sample > $null; $env:PORT = "8080"; python app.py
  • macOS / Linux:

    cd projects/staffing-assistant
    python staffing_data.py --sample > /dev/null && PORT=8080 python app.py

Open http://127.0.0.1:8080/health. Stop with Ctrl+C, run Remove-Item Env:PORT in PowerShell, and cd ../...

Step 3: Push to the BTP trial (sketch)

  1. cf login with your trial's API endpoint, then, from projects/staffing-assistant: cf push.
  2. Open the route cf push prints and add /health.
  3. After the demo: cf stop staffing-assistant. State and log on a container are lost on restart. That is fine for a demo and wrong for production, where the log must be kept at least six months.

What the files do

File What it does
requirements.txt Tells the buildpack this is a Python app; installs nothing
runtime.txt Python version for the buildpack
manifest.yml App name, memory, start command (data first, then the app) and health check
.cfignore Keeps keys, local data, state, logs and the evaluation out of the upload

If something goes wrong

What you see What it means What to do
cf: command not found The CLI isn't installed See the Unit 5 setup
The app crashes at start The start command failed Run cf logs staffing-assistant --recent and look for the Python error
Health check fails The app listens on the wrong interface Keep main() as written: it listens on all interfaces when PORT is set

Stage 6: Evaluation

Before you start: Stages 1 and 2 above. Building an evaluation harness explains gates and test sets.

A staffing ranking can't be scored like a classifier: there is no "right" person, only the person a manager chose and whether it worked. This stage asks four narrower questions:

  1. Would the people managers actually chose have been on the shortlist (the top three)? On ten past requests, with confirmed skills only, and as if every employee had reviewed their suggested skills.
  2. Do people with a data gap stay visible? Every chosen person who had an empty or pending profile must appear on the shortlist or under Also consider.
  3. Does anything but skills move a score? Change everyone's cost center, shift and hire date; every score must stay the same. This is a check that the ranking reads only what it should, not a full bias audit.
  4. Do explanations add up, and does the same input give the same ranking?

What you need

  • About 15 minutes. Free.

Step 1: Save and run the evaluation

  1. Create projects/staffing-assistant/evaluate.py, paste the code below and save.
"""Stage 6: score the ranking on past staffing decisions and test its fairness rules.

How to run (from your orchestrate-course folder, with .venv turned on):
    python projects/staffing-assistant/evaluate.py

Reads data/ and eval/history.json, writes eval/report.md. Changes no state and no log.
Built-in Python only, no randomness. The history is made up: the numbers show the method,
not a result from a real SAP system.
"""
import copy
import json
import sys
from pathlib import Path

import staffing as st

HERE = Path(__file__).resolve().parent
REPORT = HERE / "eval" / "report.md"
GATES = {"hit3_reviewed": 0.8, "gap_visible": 1.0, "flip": 1.0, "explained": 1.0, "same_twice": 1.0}


def as_request(case: dict) -> dict:
    return {"id": case["id"], "purpose": "fill_role", "job": None, "manager": "none",
            "start": case["opened"], "end": None, "needs": case["needs"], "must_have": []}


def pool_data(d: dict, case: dict) -> dict:
    dd = copy.deepcopy(d)
    dd["people"] = [p for p in dd["people"] if p["pnr"] in case["pool"]]
    return dd


def flipped(d: dict) -> dict:
    """Same skills, different everything else: cost center, shift, hire date."""
    dd = copy.deepcopy(d)
    for i, p in enumerate(dd["people"]):
        p["cost_center"] = "CP11-999"
        p["shift"] = 2 if p["shift"] == 1 else 1
        p["hired"] = f"20{10 + i:02d}-01-01"
    return dd


def main() -> int:
    d = st.load()
    history = json.loads((HERE / "eval" / "history.json").read_text(encoding="utf-8"))
    everyone = {p["pnr"]: "review" for p in d["people"] if st.infer(p["pnr"], d)}
    rows, n = [], len(history)
    hit_conf = hit_rev = gap_cases = gap_seen = flip_ok = expl_ok = expl_n = same = 0
    for case in history:
        req, dd = as_request(case), pool_data(d, case)
        r_conf = st.ranking(req, dd, {})
        r_rev = st.ranking(req, dd, everyone)
        pos = lambda r: next(x["position"] for x in r["rows"] if x["pnr"] == case["chosen"])
        c, v = pos(r_conf), pos(r_rev)
        hit_conf += c <= st.SHORTLIST
        hit_rev += v <= st.SHORTLIST
        chosen_row = next(x for x in r_conf["rows"] if x["pnr"] == case["chosen"])
        if {"PORTFOLIO_EMPTY", "SKILLS_PENDING"} & set(chosen_row["flags"]):
            gap_cases += 1
            gap_seen += case["chosen"] in r_conf["shortlist"] + r_conf["also_consider"]
        f = st.ranking(req, flipped(dd), {})
        flip_ok += [(x["pnr"], x["score"]) for x in f["rows"]] == \
                   [(x["pnr"], x["score"]) for x in r_conf["rows"]]
        for x in r_conf["rows"] + r_rev["rows"]:
            expl_n += 1
            expl_ok += sum(l["points"] for l in x["lines"]) == x["points"]
        same += st.ranking(req, dd, {}) == r_conf
        rows.append((case["id"], case["chosen"], c, v, chosen_row["flags"]))

    m = {"hit3_confirmed": hit_conf / n, "hit3_reviewed": hit_rev / n,
         "gap_visible": gap_seen / gap_cases if gap_cases else 1.0, "flip": flip_ok / n,
         "explained": expl_ok / expl_n, "same_twice": same / n}
    lines = ["# Staffing assistant: evaluation", "",
             "Synthetic data: made-up past staffing decisions at Calder (fictional). It shows the "
             "method, not a result from a real SAP system.", "",
             "| Case | Chosen | Position, confirmed skills only | Position, suggested skills reviewed | Flags then |",
             "| --- | --- | --- | --- | --- |"]
    for cid, who, c, v, flags in rows:
        lines.append(f"| {cid} | {who} | {c} | {v} | {', '.join(flags)} |")
    lines += ["", "| Measure | Value | Gate |", "| --- | --- | --- |"]
    top = f"Chosen person on the shortlist (top {st.SHORTLIST})"
    labels = {"hit3_confirmed": f"{top}, confirmed skills only",
              "hit3_reviewed": f"{top}, suggested skills reviewed",
              "gap_visible": "Chosen people with a data gap shown (shortlist or also consider)",
              "flip": "Same scores when cost center, shift and hire date change",
              "explained": "Explanation lines add up to the score",
              "same_twice": "Same input, same ranking"}
    ok = True
    for k, label in labels.items():
        gate = GATES.get(k)
        verdict = "report only" if gate is None else ("PASS" if m[k] >= gate else "FAIL")
        ok &= verdict != "FAIL"
        lines.append(f"| {label} | {m[k]:.0%} | {verdict}{'' if gate is None else f' (at least {gate:.0%})'} |")
    REPORT.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print("\n".join(lines[4:]))
    print(f"\nWrote {REPORT.relative_to(HERE).as_posix()}. Gates: {'all PASS' if ok else 'FAILED'}")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
  1. Run it:

    python projects/staffing-assistant/evaluate.py
| Case | Chosen | Position, confirmed skills only | Position, suggested skills reviewed | Flags then |
| --- | --- | --- | --- | --- |
| H-01 | 00100117 | 1 | 1 |  |
| H-02 | 00100196 | 1 | 1 |  |
| H-03 | 00100142 | 1 | 1 |  |
| H-04 | 00100205 | 4 | 1 | PORTFOLIO_EMPTY, SKILLS_PENDING |
| H-05 | 00100188 | 1 | 1 |  |
| H-06 | 00100205 | 4 | 2 | PORTFOLIO_EMPTY, SKILLS_PENDING |
| H-07 | 00100153 | 1 | 1 |  |
| H-08 | 00100188 | 2 | 1 | SKILLS_PENDING |
| H-09 | 00100211 | 1 | 1 |  |
| H-10 | 00100205 | 5 | 2 | PORTFOLIO_EMPTY, SKILLS_PENDING |

| Measure | Value | Gate |
| --- | --- | --- |
| Chosen person on the shortlist (top 3), confirmed skills only | 70% | report only |
| Chosen person on the shortlist (top 3), suggested skills reviewed | 100% | PASS (at least 80%) |
| Chosen people with a data gap shown (shortlist or also consider) | 100% | PASS (at least 100%) |
| Same scores when cost center, shift and hire date change | 100% | PASS (at least 100%) |
| Explanation lines add up to the score | 100% | PASS (at least 100%) |
| Same input, same ranking | 100% | PASS (at least 100%) |

Wrote eval/report.md. Gates: all PASS

The table tells the story of the project. On confirmed skills alone, the person the manager chose was in the top three in 7 of 10 cases; the three misses are all 00100205, whose profile was empty. Once suggested skills are reviewed, all ten are. The gate on visibility matters more than the hit rate: even before review, the assistant never hid him.

Two limits to say out loud in your report. The history uses today's work records, so an evaluation of a real system must use the evidence that existed on each request's date. And ten cases are too few for any claim beyond "the method works"; a real evaluation needs every past request and a review of which groups have thin profiles.

Step 2: Break it on purpose

  1. Open staffing.py and change SHORTLIST = 3 to SHORTLIST = 1. Run evaluate.py again. The reviewed shortlist rate falls to 80%, still passing, and the data-gap row stays at 100%, because Also consider still shows him. Set it back to 3.
  2. In staffing_data.py, add "date_of_birth": "1980-01-01", to the first person in PEOPLE, run the data script and then evaluate.py. It stops with PROTECTED_FIELD before ranking anything. Remove the line and run the data script again.

What the code does

Part What it does
as_request(), pool_data() Turns a past case into a request and limits people to that case's pool
everyone Treats every employee with suggested skills as having reviewed them
flipped() Copies the data with every non-skill field changed
Gates Top-three hit rate after review at least 80%; data gaps visible, flip test, explanations and repeatability all at 100%
eval/report.md The report for your portfolio

If something goes wrong

What you see What it means What to do
FileNotFoundError: ... history.json Stage 1 didn't run Run staffing_data.py --sample
ModuleNotFoundError: No module named 'staffing' evaluate.py isn't in the same folder as staffing.py Keep all files in projects/staffing-assistant
A gate says FAIL after your change Your change broke a rule the gate protects Read which row failed; undo or fix the change

Stage 7: Business KPI

Before you start: Stage 2 with a clean run of Steps 2 to 6 (after reset), so the log holds three offers.

The KPI comes from the assistant's own log, not from a separate spreadsheet: request open dates from the decisions, offer dates from the --on lab dates you gave.

Step 1: Save and run the KPI script

  1. Create projects/staffing-assistant/kpi.py, paste the code below and save.
"""Stage 7: time to staff a role, from the assistant's own log, with its guardrails.

How to run (from your orchestrate-course folder, with .venv turned on):
    python projects/staffing-assistant/kpi.py

Reads eval/history.json (the made-up baseline) and logs/events.jsonl. Changes nothing.
"""
import json
import sys
from datetime import date
from pathlib import Path
from statistics import median

import staffing as st

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


def days(a: str, b: str) -> int:
    return (date.fromisoformat(b) - date.fromisoformat(a)).days


def main() -> int:
    history = json.loads((HERE / "eval" / "history.json").read_text(encoding="utf-8"))
    events = st.read_log()
    before = [days(h["opened"], h["staffed"]) for h in history]
    offers = [e for e in events if e["kind"] == "decide" and e["outcome"] == "offer"]
    after = [days(e["opened"], e["on"]) for e in offers]
    explained = sum(any(x["kind"] == "explain" and x["run"] == e["run"] and x["pnr"] == e["pnr"]
                        and x["by"] == e["by"] and x["hash"] != e["hash"] for x in events)
                    for e in offers)
    by_agent = sum(e["kind"] == "decide" and e["by"].startswith("AGT_") for e in events)
    refused = {}
    for e in events:
        if e["kind"] == "refused":
            refused[e["code"]] = refused.get(e["code"], 0) + 1
    ok_log, n_events, _ = st.verify_log()

    print("Time to staff a role: days from request opened to the manager's recorded offer")
    print(f"  Before (made-up history, {len(before)} requests): median {median(before):g} days")
    if after:
        print(f"  With the assistant ({len(after)} offers in the log): median {median(after):g} days")
        for e, n in zip(offers, after):
            print(f"    {e['request']}  opened {e['opened']}  offer {e['on']}  {n} days  "
                  f"to {e['pnr']} (position {e['position']})")
        print(f"  Target: at most {TARGET_DAYS} days: {'MET' if median(after) <= TARGET_DAYS else 'NOT MET'}")
    else:
        print("  With the assistant: no offers in the log yet")
    print("\nGuardrails")
    print(f"  Decisions recorded by an agent: {by_agent} (must be 0)")
    print(f"  Offers whose decider opened the explanation first: {explained} of {len(offers)}")
    print(f"  Offers outside the shortlist: {sum(e['outside_shortlist'] for e in offers)} (allowed, with a reason)")
    print(f"  Refused attempts: {', '.join(f'{k} {v}' for k, v in sorted(refused.items())) or 'none'}")
    print(f"  Log: {'intact' if ok_log else 'BROKEN'}, {n_events} events")
    print("\nSynthetic data: the numbers show the method, not a result from a real SAP system.")
    healthy = by_agent == 0 and explained == len(offers) and ok_log
    return 0 if healthy else 1


if __name__ == "__main__":
    sys.exit(main())
  1. Run it:

    python projects/staffing-assistant/kpi.py
Time to staff a role: days from request opened to the manager's recorded offer
  Before (made-up history, 10 requests): median 28.5 days
  With the assistant (3 offers in the log): median 2 days
    SR-0001  opened 2026-11-23  offer 2026-11-25  2 days  to 00100205 (position 1)
    SR-0002  opened 2026-11-24  offer 2026-11-26  2 days  to 00100188 (position 1)
    SR-0003  opened 2026-11-25  offer 2026-11-27  2 days  to 00100231 (position 1)
  Target: at most 10 days: MET

Guardrails
  Decisions recorded by an agent: 0 (must be 0)
  Offers whose decider opened the explanation first: 3 of 3
  Offers outside the shortlist: 0 (allowed, with a reason)
  Refused attempts: AGENT_DECIDES 1, NOT_ALLOWED 2, PURPOSE 1, STALE_RUN 1
  Log: intact, 20 events

Synthetic data: the numbers show the method, not a result from a real SAP system.

Read the guardrails before the headline. Zero agent decisions, every offer explained first, and an intact log are what make the days count. The refused attempts are worth showing too: they prove the controls were tried and held.

What the code does

Part What it does
before Days from opened to staffed for each past request (baseline)
offers, after Offer decisions from the log and their days since the request opened
explained Offers whose decider opened that person's explanation in that run first
by_agent, refused Decisions by agents (must be zero) and refusals by code
Exit code 1 if a guardrail fails, so a pipeline can stop on it

If something goes wrong

What you see What it means What to do
no offers in the log yet You ran reset and haven't decided Repeat Stage 2, Steps 2 to 6
More offers than three You decided requests in Stage 4 as well Fine; or reset and repeat Stage 2 for the page's numbers
Log: BROKEN A log line was edited Expected if you tried the tamper test; reset and repeat

Human in the loop

Every decision about a person in this project is made by a person, and the code enforces it:

  • decide() is the only way to record a decision. It refuses any agent user, anyone but the request's hiring manager or HR, the candidate themselves, and a reason shorter than 20 characters.
  • The decision follows the explanation. The decider must have opened that person's explanation in that run; the log proves it.
  • Decisions use current data. A run whose inputs changed, or that isn't the latest for the request, is refused.
  • Suggested skills are the employee's to accept. Nobody else can turn evidence into counted skills.
  • Nothing is rejected by the list. People left out are listed with the rule, and anyone can be chosen from anywhere on the list, with a reason.
  • The assistant refuses work it wasn't approved for, and refuses to start before notice was given.

What people decide that code doesn't: whether a training need can be met in time, whether the person wants the move, and whether the reason they wrote would stand up if the employee asked.

Production gap

What would change for a real customer:

Identity and authorizations

  • Replace the X-Lab-User header with sign-on (SAP Cloud Identity Services on BTP, as sketched in Unit 5) and take roles from the token. Map hiring managers to the requests they own, from the source system.
  • Give the agent its own technical user that every decision path refuses, in SuccessFactors as in the assistant. Agent permissions and SAP authorizations covers the pattern.
  • Use SuccessFactors' role-based permissions for who sees whose skills; SAP Learning describes a Growth Portfolio permission category (SAP Learning).

Data, privacy and the law

  • Read skills, requests and people through released SuccessFactors APIs, never a full HR export, and list the fields you take. Keep the forbidden-field check.
  • Work records with names of other people, health remarks or free-text comments need masking before they become evidence. Data security and PII covers it.
  • Have legal confirm the use-case classification, the notice texts, works council agreements where they apply, and log retention (EU AI Act topic, US state AI laws topic). The six-month minimum is a floor; your retention policy may set more, and privacy law may set limits.
  • Review profile completeness by team before go-live: if one shift or site has thin profiles, the assistant will under-rank it.

Operations

  • Move state and the log to a database with backups and write-once storage for the log. Files on a container vanish on restart.
  • Run evaluate.py and the tests in your build pipeline; block a release when a gate fails. Version the rules (staffing-rules 1.0) and re-evaluate on every change.
  • Have someone read the refusals weekly. A burst of PURPOSE or NOT_ALLOWED refusals is a training or a misuse signal.

Cost

  • The matching costs nothing per run. The real cost is people: keeping skills current, reviewing suggestions, and oversight.

Clean core and SAP's own options

The assistant is a side-by-side app that reads HR data and writes nothing back to SuccessFactors. Before building, check SAP's route, as of 25 November 2026:

Need Build (this project) SAP
Recommend internal opportunities by skills Simple rule-based ranking with explanations Opportunity Marketplace Intelligent Recommendations (data minimums apply) and Personalized Opportunities Recommendation (AI Units) (SAP Learning, SAP)
Keep skills and suggested skills portfolios.json and consent Growth portfolio in Talent Intelligence Hub; AI-assisted skill recommendations need AI Units
Assignments with approvals A decision gate Opportunity Marketplace assignments with approvers for applications and offers (SAP Learning)
Write assignment texts Not covered Assignment Creation, sold within Joule Premium for Human Capital Management (SAP)
Notice, purpose limits, chained decision log Built in Ask SAP and your team how these are covered in your configuration; as the company using the system, you hold the deployer's duties either way

Portfolio checklist

Put the project in your public portfolio repository from Set up for Unit 12. It should contain:

  1. README.md with the problem (slow internal staffing, invisible skills), the KPI (time to staff a role, baseline, target and guardrails) and how to run each stage.
  2. Architecture diagram: the stage overview or the sequence diagram from Stage 2.
  3. Run instructions that work on a fresh clone with --sample and no account, in stage order.
  4. Evaluation report: eval/report.md, with three sentences on what the profile gap taught you and the two limits from Stage 6.
  5. A one-page design summary: the scoring rule, the flags, the seven controls from Risks and controls, who may do what, and what the Production gap would change.
  6. A 3-minute demo script: the one in the foundational layer, rehearsed with the page.

Leave out data/, state/, logs/ and .env. Save your work:

git add .gitignore projects/staffing-assistant
git status

Check that git status lists no data/, state/ or logs/ files, then:

git commit -m "Project: HR staffing assistant"

Accepting suggested skills is the employee's choice, so withdrawing it must be too. Add a revoke command: only the employee can use it, the suggested skills stop counting, and any ranking made before is stale.

  1. Open staffing.py. Below the accept() function, add:

    def revoke(pnr: str, by: str, d: dict, state: dict) -> None:
        """The employee withdraws consent: suggested skills stop counting from now on."""
        check_user(by, d)
        if by != pnr:
            raise Refused("NOT_ALLOWED", "only the employee can withdraw their own consent")
        if pnr not in state["accepted"]:
            raise Refused("NOTHING_TO_REVOKE", f"{pnr} hasn't accepted suggested skills")
        del state["accepted"][pnr]
        save_state(state)
        log_event("revoke", d["today"], pnr=pnr, by=by)
  2. In main(), below the line p = sub.add_parser("accept"); p.add_argument("pnr"); p.add_argument("--by", required=True), add:

        p = sub.add_parser("revoke"); p.add_argument("pnr"); p.add_argument("--by", required=True)
  3. Still in main(), above the line elif args.cmd == "decide":, add:

            elif args.cmd == "revoke":
                revoke(args.pnr, args.by, d, state)
                print(f"{args.pnr} withdrew consent; suggested skills no longer count")
  4. In test_staffing.py, add this test inside the Controls class:

        def test_revoke_makes_runs_stale(self):
            run = self.ready_run()
            self.refused("NOT_ALLOWED", st.revoke, "00100205", "00100153", self.d, self.s)
            st.revoke("00100205", "00100205", self.d, self.s)
            self.refused("STALE_RUN", st.decide, run, "00100205", "offer", "00100153",
                         REASON, self.d, self.s)
  5. Run python projects/staffing-assistant/staffing.py reset, then: accept 00100205 --by 00100205, rank SR-0001 --by 00100153, revoke 00100205 --by 00100205, rank SR-0001 --by 00100153 (each as python projects/staffing-assistant/staffing.py ...).

  6. Add one sentence to your design summary: what happens to a decision already recorded when the employee later withdraws consent, and who should review it.

Done when the last ranking shows 00100205 at 0% with PORTFOLIO_EMPTY and SKILLS_PENDING again, verify-log reports the log intact with a revoke event in logs/events.jsonl, and test_staffing.py runs 14 tests with OK.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Why is the score built from one line per needed skill rather than produced by a language model?

Answer: A. In a high-risk use the score must be explainable and repeatable. The explanation is the same set of lines that made the score, and the evaluation checks they add up and that the same input gives the same ranking.

2The rework technician accepts his suggested skills after RUN-0001. The manager then tries to decide on RUN-0001. What happens, and why?

Answer: A. decide() compares the run's input fingerprint with the current data and requires the latest run for the request. A decision must rest on the ranking of the data as it is now.

3Which check makes sure a decision follows the explanation?

Answer: A. The log records every explanation with who opened it. decide() refuses with NOT_EXPLAINED unless that person opened that candidate's explanation in that same run.

4An HR extract arrives with a date_of_birth field on one person. What does the assistant do?

Answer: B. The assistant must never see protected data. Stopping is safer than dropping quietly, because it forces someone to fix the extract that sent it.

5What does the flip test in evaluate.py show?

Answer: A. The flip test shows the ranking reads only skills. It is not a full bias audit; groups with thin profiles can still rank low, which is why data gaps are flagged and profile completeness should be reviewed.

6You deploy the demo to the BTP trial for a stakeholder meeting. What must you do afterwards, and why?

Answer: D. The X-Lab-User header is a stand-in with no sign-on. The demo is safe only on made-up data and only while someone is watching it; production replaces it with real sign-on and roles from the token.

7Why does the log carry the previous line's fingerprint?

Answer: A. Each line's fingerprint covers the previous one, so any change breaks every check after it. A log people can quietly edit would prove nothing to an auditor or to the employee who asks.

8Your company licenses SuccessFactors Opportunity Marketplace with Intelligent Recommendations. What do you take from this project?

Answer: D. SAP's features cover recommendations and assignment approvals. Notice, purpose limits, consent for suggested skills, explanations and a kept log are still the company's job as deployer, so check how your configuration covers each.
NextProject: a cross-platform agent (Copilot Studio and Bedrock to SAP, one identity)Build one governed SAP entry that a Copilot Studio agent and a Bedrock agent both use, over MCP and A2A, with each person's own SAP identity.

Sources

  • SAP SuccessFactors Career and Talent Development, Personalized Opportunities Recommendation (sap.com) — read 25 November 2026; AI feature matching employees to opportunities by skills and seniority, with learning recommendations from skill gaps; names Opportunity Marketplace and Career and Talent Development; AI Units currently required, activated with AI Units; no date or status label on the page
  • SAP SuccessFactors Opportunity Marketplace (sap.com) — read 25 November 2026; intelligent skills framework recommending opportunities; recommendations for learning, mentors and temporary assignments; no prices or editions on the page
  • AI and Machine Learning in Opportunity Marketplace (SAP Learning) — read 25 November 2026; Intelligent Recommendations powered by SAP AI Business Services, in Top Picks for You, Ignite Your Role and Reach Your Aspirations; data minimums (1,000 activity items, 100 users, 100 items); switched on by an administrator, about nine days to generate; generative assignment creation and skill recommendation called premium
  • Using Opportunity Marketplace Assignments (SAP Learning) — read 25 November 2026; assignment lifecycle: owners publish, approvers approve applications and offers, owners send offers, applicants accept, assignments start and close; generative creation needs an AI Units license; completed assignments update the growth portfolio when Talent Intelligence Hub is on
  • Navigating Opportunity Marketplace (SAP Learning) — read 25 November 2026; opportunity sources (assignments, internal job postings, learning, mentoring, suggested roles); assignments usually shorter than 12 months; personalized learning recommendations described as in early adoption
  • Describing the Growth Portfolio (SAP Learning) — read 25 November 2026; growth portfolio in Talent Intelligence Hub; AI-assisted skill recommendations need an AI Units license; attributes created as inferred must be confirmed before employees see them; business rule workflow for assigned ratings with the manager as approver (example GP_Approval)
  • Exploring Integrations with Talent Intelligence Hub (SAP Learning) — read 25 November 2026; attribute libraries hold skills and competencies; completed assignments, performance and 360 reviews, role readiness forms and learning write ratings into the growth portfolio; recruiting requisitions take skills from the library; no API names on the page
  • SAP SuccessFactors Opportunity Marketplace, Assignment Creation (sap.com) — read 25 November 2026; generative creation and editing of assignments; AI Units required; sold only within the Joule Premium for Human Capital Management package

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in