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.
A day in the life at Calder after go-live, Wednesday 25 November 2026:
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).
08:00. The employee sees his suggested skills, from nine confirmed repair jobs, and accepts them. Only he can do that.
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.
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.
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.
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.
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.
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
The pain (30 s). Ten past requests, median 28.5 days. The rework technician ranked near the bottom on an empty profile.
The consent (45 s). As the employee, accept the suggested skills. Rank again: first, with a training need.
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.
The boundary (30 s). Ask it to pick someone to let go: refused, and the refusal is in the log.
The proof (15 s). The evaluation report and the KPI, said plainly to be made-up data.
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.
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
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"]
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:
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.
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.
About 10 minutes. No cost, no account, no internet.
#Step 1: Open the course folder and turn on the environment
Open VS Code, choose File > Open Folder and open orchestrate-course.
Open a terminal: Terminal > New Terminal.
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.
The script regenerates data/; state/ holds runs, consents and decisions; logs/ holds the chained log. The eval/ folder stays: its report is portfolio material.
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.
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.
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
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())
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.
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.
Try to accept his skills for him, as the manager. It is refused:
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%.
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
REFUSED NOT_ALLOWED: 00100142 may see only their own explanation
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:
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.
Ask for the request the assistant was never approved for:
REFUSED PURPOSE: SR-0004 asks for 'reduce_headcount'. The assistant is approved only for ['assignment', 'fill_role']; anything else needs a new assessment
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.
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
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
cf login with your trial's API endpoint, then, from projects/staffing-assistant: cf push.
Open the route cf push prints and add /health.
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.
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:
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.
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.
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.
Do explanations add up, and does the same input give the same ranking?
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())
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.
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.
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.
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.
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())
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.
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.
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).
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.
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.
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:
Put the project in your public portfolio repository from Set up for Unit 12. It should contain:
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.
Architecture diagram: the stage overview or the sequence diagram from Stage 2.
Run instructions that work on a fresh clone with --sample and no account, in stage order.
Evaluation report: eval/report.md, with three sentences on what the profile gap taught you and the two limits from Stage 6.
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.
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:
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.
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)
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)
Still in main(), above the line elif args.cmd == "decide":, add:
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.
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.
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