CX Discovery Notebook

This commit is contained in:
2026-07-23 12:04:37 -04:00
parent cbbc9ba839
commit 71b913d7fe
45 changed files with 23170 additions and 1830 deletions

View File

@@ -0,0 +1,83 @@
# 202607 — CX Exploration & Discovery Workshop
A **live facilitation aid** for a CX discovery session, built on the
[Mercury Notebook Deliverable Pattern](../../docs/Mercury_Notebook_Pattern_V1-00.md).
Unlike the TEI business-case studies, this deliverable computes no dollars —
its "numbers" are **topic status and progress**. The Mercury stage is the
visual you share on a call or in a workshop while you work through the
questions; the question script and captured notes live backstage and export
as LLM input for the survey write-up or a downstream business case.
## What the client sees (the stage)
A calm **topic board**: each topic, its one-line scope, a status glyph, and —
for the topic under discussion — a **live sub-topic checklist**, above a
**progress bar** ("3/8 topics complete"). No wall of questions: you ask those.
![board preview](docs/board_preview.png)
You drive it from the sidebar — a **status** selector and a **notes** box per
topic, plus a **checkbox** per sub-topic. As the conversation moves you set a
topic *In progress*, tick sub-topics as you cover them, mark it *Complete* (or
*Skipped*), and jot answers. Every change re-renders the board and progress bar
(Mercury re-runs the cells below the widgets).
## What you work from (backstage)
JupyterLab and the exports carry the **facilitator question script** (all 95
prompts, grouped by topic → sub-topic) and the **captured-session appendix**
(status + notes as a markdown table and one JSON block). Neither shows on the
Mercury stage. The 8 topics / 26 sub-topics / ~110-minute agenda are the
structured form of the source survey.
## Layout
```
discoverylib/ # the engine — all content & logic
topics.py # the topic bank (verbatim anchor from the survey)
session.py # status vocabulary, progress, checklist, export payload
staging.py # stage/backstage detection (copied verbatim)
notebooks/cx_discovery.ipynb # the deliverable (generated — see below)
scripts/
build_notebook.py # regenerates the notebook from cell sources
export_report.py # nbconvert → exports/*.html + *.md
tests/ # engine pins + stage/backstage test
docs/cx_discovery_survey.md # source survey (the original cxxm.md)
exports/ # generated report sources
```
## The notebook is generated
The notebook wires ~42 Mercury widgets (a status selector + notes box per
topic, a checkbox per sub-topic), all derived from the topic bank so they can't
drift from `discoverylib`. Rather than hand-maintain that JSON, the notebook is
built from readable cell sources in
[`scripts/build_notebook.py`](scripts/build_notebook.py):
```bash
python scripts/build_notebook.py # regenerate after editing a cell
```
Edit facilitation *content* (topics, sub-topics, prompts, scope, minutes) in
[`discoverylib/topics.py`](discoverylib/topics.py) — not in the notebook.
## Run
```bash
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
mercury --working-dir . # serve the stage (share this screen)
jupyter lab # analyst / facilitator view
pytest # engine pins + stage/backstage
jupyter nbconvert --to notebook --execute --inplace notebooks/cx_discovery.ipynb # gate
python scripts/export_report.py # exports/*.html + *.md for the LLM handoff
```
## Extending
New or reshaped discovery content is a `discoverylib/topics.py` edit, a test
pin (`tests/test_topics.py` recounts, `tests/test_session.py` for new logic),
then `python scripts/build_notebook.py`. Add a topic and the sidebar controls,
board, checklist, script, gate, and export all pick it up — because they're all
generated from the bank.

View File

@@ -0,0 +1,73 @@
# Mercury app-shell theme — NTT DATA brand (light), modern surfaces.
# See docs/brand.md for the source palette. Loaded from the directory where
# you launch `mercury` (this study root); restart the server to apply.
[main]
title = "CX Discovery Workshop"
favicon_emoji = "🧭"
footer = "CX Exploration & Discovery Workshop"
notebooks_button_label = "Workshops"
[welcome]
header = "CX Discovery Workshop"
message = """
The live visual for a CX exploration & discovery session. Topics and
progress render on screen for the client; the facilitator drives the
question script and captures notes backstage. Mark each topic's status in
the sidebar as the conversation moves — the board and the progress bar
update live. Afterward, export the captured notes for drafting with
`python scripts/export_report.py`.
"""
[theme]
# ── Type — Georgia headings, Arial body (web-safe; no network fetch). ──
font_family = "Arial, 'Helvetica Neue', Helvetica, sans-serif"
heading_font_family = "Georgia, 'Times New Roman', Times, serif"
font_size = "15px"
font_weight = "normal"
heading_font_weight = "700"
# ── Text — NTT ink scale ──
text_color = "#2e404d"
muted_text_color = "#586671"
# ── Surfaces — white content on a soft neutral canvas ──
background_color = "#f4f5f6"
content_background_color = "#ffffff"
surface_color = "#ffffff"
card_background_color = "#f8f8f8"
border_color = "#d5d9db"
border_radius = "10px"
# ── Accents — Future Blue ──
primary_color = "#0072bc"
accent_color = "#0072bc"
focus_border_color = "#0072bc"
hover_background_color = "#eef5fb"
selected_background_color = "#dcecfa"
# ── Sidebar — clean white, hairline divider ──
sidebar_background_color = "#ffffff"
sidebar_text_color = "#2e404d"
sidebar_title_color = "#151d2c"
sidebar_shadow = "1px 0 0 #d5d9db"
# ── Top bar — deep NTT navy ──
topbar_background_color = "#151d2c"
topbar_text_color = "#ffffff"
topbar_border_color = "rgba(255,255,255,0.08)"
# ── Footer ──
footer_background_color = "#ffffff"
footer_text_color = "#586671"
footer_border_color = "#d5d9db"
# ── Run button — subtle brand-blue gradient ──
run_button_background = "linear-gradient(180deg, #0087dc 0%, #0072bc 100%)"
run_button_background_hover = "linear-gradient(180deg, #1a93e6 0%, #0079c8 100%)"
run_button_text_color = "#ffffff"
# ── Depth — soft, navy-tinted shadows ──
shadow_sm = "0 1px 2px rgba(21,29,44,0.05)"
shadow_md = "0 6px 18px rgba(21,29,44,0.08)"
shadow_lg = "0 16px 40px rgba(21,29,44,0.10)"

View File

@@ -0,0 +1,62 @@
"""
discoverylib — self-contained engine for the CX Exploration & Discovery
Workshop (Mercury Notebook Pattern).
Not a financial model: this study's deliverable is a **live facilitation
aid**. The Mercury stage is the visual the client watches on the call —
topic board, the active topic's live sub-topic checklist, and a progress
headline ("3/8 topics complete"). The backstage (JupyterLab / nbconvert)
carries the facilitator's question script and the captured per-topic notes,
which the data-appendix export hands to an LLM to draft the survey write-up
or feed a downstream business-case study.
Engine/presentation split (Pattern §2): the topic bank and all status /
progress logic live here; the notebook only arranges and renders them.
"""
from .topics import (
TOPIC_BY_KEY,
TOPIC_KEYS,
TOPICS,
SubTopic,
Topic,
topic,
)
from .session import (
COMPLETE,
IN_PROGRESS,
NOT_STARTED,
SKIPPED,
STATUS_COLOR,
STATUS_GLYPH,
STATUS_LABEL,
STATUSES,
ChecklistItem,
Progress,
TopicState,
active_topic_key,
agenda_minutes,
build_session,
normalize_status,
progress,
session_json,
subtopic_checklist,
subtopic_id,
)
from .staging import backstage, on_stage
__version__ = "0.1.0"
__all__ = [
# topic bank
"TOPICS", "TOPIC_BY_KEY", "TOPIC_KEYS", "Topic", "SubTopic", "topic",
# status vocabulary
"STATUSES", "STATUS_LABEL", "STATUS_GLYPH", "STATUS_COLOR",
"NOT_STARTED", "IN_PROGRESS", "COMPLETE", "SKIPPED", "normalize_status",
# progress + session
"Progress", "progress", "active_topic_key", "agenda_minutes",
"ChecklistItem", "subtopic_checklist", "subtopic_id",
"TopicState", "build_session", "session_json",
# staging
"on_stage", "backstage",
]

View File

@@ -0,0 +1,251 @@
"""
Session engine — the discovery workshop's "math".
There are no dollars here; the quantities a facilitator and client watch are
**status** and **progress**. This module owns all of it so the notebook only
arranges outputs (Mercury Notebook Pattern §2, engine/presentation split):
* the topic-status vocabulary (:data:`STATUSES`) and its display glyphs,
* :func:`progress` — the "3 / 8 topics complete" headline and its ratios,
* :func:`subtopic_checklist` — the live tick-list for the active topic,
* :func:`build_session` — assembles the full render/export state from the
raw widget inputs (per-topic status + free-text notes),
* :func:`session_json` — the machine-readable export payload (Pattern §5).
Everything is a pure function of ``(status_by_topic, notes_by_topic,
done_subtopics)`` so the in-notebook gate can pin it and the export can dump
it. Unknown / missing keys degrade gracefully to "not started" so a
half-filled live session never crashes the render.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from .topics import TOPICS, TOPIC_BY_KEY, Topic
# ── Status vocabulary ────────────────────────────────────────────────
# Order matters: it's the selector order and the legend order. "skipped"
# is terminal-but-not-complete (a topic consciously set aside), so it
# counts as resolved for the agenda but not toward completion.
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
COMPLETE = "complete"
SKIPPED = "skipped"
STATUSES: tuple[str, ...] = (NOT_STARTED, IN_PROGRESS, COMPLETE, SKIPPED)
STATUS_LABEL: dict[str, str] = {
NOT_STARTED: "Not started",
IN_PROGRESS: "In progress",
COMPLETE: "Complete",
SKIPPED: "Skipped",
}
# Stage glyphs — calm, unambiguous at a glance on a shared screen.
STATUS_GLYPH: dict[str, str] = {
NOT_STARTED: "", # open circle — pending
IN_PROGRESS: "", # half — under discussion
COMPLETE: "", # filled — done
SKIPPED: "", # slashed — set aside
}
# Brand-aligned status colors (docs/brand.md). Muted gray pending, Future
# Blue active, Success Green complete, light gray skipped.
STATUS_COLOR: dict[str, str] = {
NOT_STARTED: "#a9b2b8",
IN_PROGRESS: "#0072bc",
COMPLETE: "#00a34c",
SKIPPED: "#c3c7ca",
}
def normalize_status(value: str | None) -> str:
"""Coerce any widget value to a known status; default NOT_STARTED."""
return value if value in STATUS_LABEL else NOT_STARTED
# ── Progress ─────────────────────────────────────────────────────────
@dataclass(frozen=True)
class Progress:
"""The headline the client watches: completed vs. total topics, plus
the resolved (complete + skipped) count that drives the agenda burn."""
total: int
completed: int # status == complete
skipped: int
in_progress: int
not_started: int
@property
def resolved(self) -> int:
"""Topics no longer open for discussion (complete or skipped)."""
return self.completed + self.skipped
@property
def fraction(self) -> float:
"""Completed / total in [0, 1] — the progress-bar fill."""
return self.completed / self.total if self.total else 0.0
@property
def label(self) -> str:
return f"{self.completed}/{self.total} topics complete"
def progress(status_by_topic: dict[str, str]) -> Progress:
"""Tally topic statuses into the headline :class:`Progress`."""
counts = {s: 0 for s in STATUSES}
for t in TOPICS:
counts[normalize_status(status_by_topic.get(t.key))] += 1
return Progress(
total=len(TOPICS),
completed=counts[COMPLETE],
skipped=counts[SKIPPED],
in_progress=counts[IN_PROGRESS],
not_started=counts[NOT_STARTED],
)
def active_topic_key(status_by_topic: dict[str, str]) -> str | None:
"""The topic to spotlight on stage: the first in-progress topic, else
the first not-started one, else None (everything resolved)."""
for t in TOPICS:
if normalize_status(status_by_topic.get(t.key)) == IN_PROGRESS:
return t.key
for t in TOPICS:
if normalize_status(status_by_topic.get(t.key)) == NOT_STARTED:
return t.key
return None
# ── Sub-topic checklist (live, for the active topic) ─────────────────
@dataclass(frozen=True)
class ChecklistItem:
key: str
title: str
done: bool
def subtopic_checklist(
topic: Topic, done_subtopics: set[str] | frozenset[str]
) -> list[ChecklistItem]:
"""The active topic's sub-topics as a tick-list. ``done_subtopics``
holds the fully-qualified ``"<topic_key>.<subtopic_key>"`` ids the
facilitator has ticked."""
return [
ChecklistItem(st.key, st.title, f"{topic.key}.{st.key}" in done_subtopics)
for st in topic.subtopics
]
def subtopic_id(topic_key: str, subtopic_key: str) -> str:
"""The fully-qualified id used in ``done_subtopics`` and the export."""
return f"{topic_key}.{subtopic_key}"
# ── Agenda ───────────────────────────────────────────────────────────
def agenda_minutes() -> int:
"""Sum of the nominal per-topic minute budgets."""
return sum(t.minutes for t in TOPICS)
# ── Full session state (render + export) ─────────────────────────────
@dataclass(frozen=True)
class TopicState:
key: str
title: str
scope: str
minutes: int
status: str
status_label: str
glyph: str
color: str
notes: str
subtopics_total: int
subtopics_done: int
def build_session(
status_by_topic: dict[str, str],
notes_by_topic: dict[str, str] | None = None,
done_subtopics: set[str] | frozenset[str] | None = None,
) -> dict[str, Any]:
"""Assemble the complete session state the notebook renders and exports.
Pure function of the three raw inputs; safe against missing keys.
"""
notes_by_topic = notes_by_topic or {}
done_subtopics = frozenset(done_subtopics or ())
topic_states: list[TopicState] = []
for t in TOPICS:
status = normalize_status(status_by_topic.get(t.key))
done = sum(
1 for st in t.subtopics if subtopic_id(t.key, st.key) in done_subtopics
)
topic_states.append(
TopicState(
key=t.key,
title=t.title,
scope=t.scope,
minutes=t.minutes,
status=status,
status_label=STATUS_LABEL[status],
glyph=STATUS_GLYPH[status],
color=STATUS_COLOR[status],
notes=(notes_by_topic.get(t.key) or "").strip(),
subtopics_total=len(t.subtopics),
subtopics_done=done,
)
)
prog = progress(status_by_topic)
active = active_topic_key(status_by_topic)
return {
"topics": topic_states,
"progress": prog,
"active_topic_key": active,
"active_topic": TOPIC_BY_KEY[active] if active else None,
"agenda_minutes": agenda_minutes(),
}
def session_json(
session: dict[str, Any], meta: dict[str, Any] | None = None
) -> dict[str, Any]:
"""The machine-readable export payload (Pattern §5): every captured
answer/status/note as plain JSON, ready to feed an LLM drafting the
survey write-up or business case. Plotly/HTML never carry this — the
appendix does."""
prog: Progress = session["progress"]
return {
"study": "202607_CX_Discovery_Workshop",
"instrument": "CX Exploration & Discovery Workshop",
"meta": meta or {},
"progress": {
"total_topics": prog.total,
"completed": prog.completed,
"skipped": prog.skipped,
"in_progress": prog.in_progress,
"not_started": prog.not_started,
"fraction_complete": round(prog.fraction, 4),
"label": prog.label,
},
"agenda_minutes": session["agenda_minutes"],
"active_topic": session["active_topic_key"],
"topics": [
{
"key": ts.key,
"title": ts.title,
"scope": ts.scope,
"status": ts.status,
"minutes": ts.minutes,
"subtopics_done": ts.subtopics_done,
"subtopics_total": ts.subtopics_total,
"notes": ts.notes,
}
for ts in session["topics"]
],
}

View File

@@ -0,0 +1,29 @@
"""
Stage vs backstage — is this notebook render stakeholder-facing?
The Mercury CLI (``mercury --working-dir …``) exports ``MERCURY_CONFIG_DIR``
into the server process so the widget library can locate ``config.toml``
(see ``mercury/config.py``); every kernel that server spawns inherits it.
JupyterLab and nbconvert kernels don't have it. That makes the variable a
reliable signal for "the audience is looking" (the stage) versus an
analyst session or a headless export run (backstage).
Diagnostics routed through :func:`backstage` stay visible in JupyterLab
and land in the nbconvert exports (where the machine-readable appendix
must appear for LLM consumption) but never render in the Mercury app.
"""
from __future__ import annotations
import os
def on_stage() -> bool:
"""True when running under the Mercury app (stakeholder-facing)."""
return os.getenv("MERCURY_CONFIG_DIR") is not None
def backstage(*args, **kwargs) -> None:
"""``print`` that renders only backstage (JupyterLab, nbconvert)."""
if not on_stage():
print(*args, **kwargs)

View File

@@ -0,0 +1,428 @@
"""
The discovery topic bank — verbatim source record for the CX Exploration &
Discovery workshop.
This is the study's ``*_VERBATIM`` anchor (Mercury Notebook Pattern): the
facilitation content, structured but **never paraphrased away from** the
source survey ``docs/cx_discovery_survey.md`` (the original ``cxxm.md``).
Editing the wording of a prompt here is editing the anchor — do it against
the survey, not the notebook.
Shape
-----
``TOPICS`` is an ordered tuple of :class:`Topic`. Each topic owns an ordered
tuple of :class:`SubTopic`; each sub-topic owns the ordered facilitator
prompts (the questions you actually ask). The stage shows topic titles, the
one-line ``scope`` per topic, and — for the active topic — the sub-topic
titles as a live checklist. The prompts stay **backstage** (your script);
they never render on the client's screen.
Every topic carries:
* ``key`` — stable slug (snake_case); the identity used by widgets, notes,
status, and the JSON export. NEVER renumber or rename casually —
captured notes key off it.
* ``title`` — client-facing heading shown on stage.
* ``scope`` — one neutral line shown under the title on stage, so the client
stays oriented without being led by the questions.
* ``minutes`` — nominal facilitation budget, summed into the agenda estimate.
The content is deliberately data, not prose in the notebook: it is testable,
diffable, and exportable, and the notebook only arranges it.
"""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass(frozen=True)
class SubTopic:
"""A discussion thread within a topic; its title shows on stage when the
topic is active, its prompts are the backstage facilitation script."""
key: str
title: str
prompts: tuple[str, ...] = ()
@dataclass(frozen=True)
class Topic:
"""A client-facing discovery topic: the unit the progress bar counts."""
key: str
title: str
scope: str
minutes: int
subtopics: tuple[SubTopic, ...] = field(default_factory=tuple)
@property
def prompt_count(self) -> int:
return sum(len(st.prompts) for st in self.subtopics)
# ── The topic bank ───────────────────────────────────────────────────
# Ordered as a workshop runs: context first, then the operational areas,
# then the enabling functions, closing on reporting & insight. Wording of
# prompts tracks docs/cx_discovery_survey.md (cxxm.md).
TOPICS: tuple[Topic, ...] = (
Topic(
key="background",
title="Background & Organization",
scope="Lines of business, channels, org structure, decision-making",
minutes=15,
subtopics=(
SubTopic(
"lines_of_business", "Lines of business & scope",
(
"How many distinct lines of business are supported in the "
"contact centre? (e.g. commercial, residential, retail, "
"wholesale)",
"Are you using the contact centre for internal uses such as "
"help desk, finance, HR?",
"Payment card / PCI in scope?",
"What are the availability SLAs or targets for your "
"technology platform?",
),
),
SubTopic(
"channels_supported", "Channels supported",
(
"Which channels do you support today? (Apps, Voice, Video, "
"Chat, SMS, Email, Social Media, Digital Assistants)",
),
),
SubTopic(
"org_structure", "Org & reporting structure",
(
"Mini org chart — reporting structure up to the executive "
"leader.",
"Are your contact centres managed by the same person? "
"(Managers / Team Leads / Agents)",
"Who carries the cost of contact centre agents and "
"supervisors?",
"What revenue is generated by the contact centre?",
),
),
SubTopic(
"decision_making", "Decision-making & priorities",
(
"Is decision-making centralized or decentralized?",
"Who are the key decision makers for changes to the contact "
"centre?",
"How important is CX & EX to your organization's strategy? "
"Is there an executive accountable for CX (CXO, CDO)?",
"Of your leading offers, what is the customer's top priority?",
"Competitive pressures?",
"Any pending or recent acquisitions or spinoffs affecting IT "
"infrastructure and services?",
),
),
SubTopic(
"problems_today", "Problems & causes today",
(
"What do you view as the problems in your contact centre "
"today, and the primary causes?",
"Any in-flight projects — CX or EX improvement initiatives?",
"Are your customer experiences personalized?",
),
),
),
),
Topic(
key="cx_strategy",
title="CX Strategy",
scope="How CX value is defined, measured, and organized to deliver",
minutes=15,
subtopics=(
SubTopic(
"value_definition", "Value & strategic position",
(
"How is the value of Customer Experience defined within your "
"organization? Is CX a key BPI, recognized & measured as a "
"financial value?",
"What are the key capabilities / services delivered by the "
"contact centre?",
"How are you using CX innovation to create market "
"disruption?",
"How are competitors using CX to create competitive "
"differentiation?",
),
),
SubTopic(
"operating_model", "Organization & operating model",
(
"Is there a CX team? Do the CX insights team regularly "
"educate the business?",
"Who are the key decision makers for investment and changes "
"to the contact centre? Channel management strategy?",
"What are the teams, and how are processes managed?",
"Describe your automation strategy. Who is your leader for "
"Data & AI?",
),
),
SubTopic(
"insight_and_voc", "Insight & Voice of Customer",
(
"How do you use analytics & data to generate a consolidated "
"view of your customer experience?",
"Is there a VOC program in place? ROI / business value "
"known?",
"How do customers rate the experience they receive (05)?",
),
),
SubTopic(
"continuous_improvement", "Continuous improvement",
(
"How is customer insight used to drive CX improvement, "
"loyalty and profitability? How do you anticipate needs?",
"Do you have a clear set of CX design guidelines? (Personas, "
"Journey Mapping, Tools)",
"KPI targets for CX — CSAT, NPS, CES? How are you doing?",
),
),
SubTopic(
"employee_engagement", "Employee engagement",
(
"Describe your employee / agent engagement strategy.",
"How engaged are your people in delivering the customer "
"experience?",
"Do you have a VoA / VoE program in place? How are you "
"doing?",
),
),
),
),
Topic(
key="channels",
title="Channels",
scope="Inbound & outbound volumes, metrics, contact reasons",
minutes=20,
subtopics=(
SubTopic(
"inbound_context", "Inbound context",
(
"Hours of operation — any 24×7?",
"Who contacts the contact centre? (Demographics, their "
"situation)",
"Are certain callers or groups prioritized?",
"Languages? (English, Canadian French, Spanish, other)",
),
),
SubTopic(
"voice_metrics", "Voice & video metrics",
(
"Average number of active agents (voice / video).",
"Toll-free numbers & DIDs — approximate quantities.",
"Average Wait Time, Abandon rate, Handle Time, Hold Time, "
"After-call work time.",
"Time to authenticate a caller.",
"% of calls transferred — internally / externally (3rd "
"parties)?",
"Courtesy callback / virtual hold? Post-call survey? First "
"Call Resolution rate? Average revenue per call (sales)?",
),
),
SubTopic(
"digital_channels", "Digital channels",
(
"Email — range of logged-in users, response time, email "
"server.",
"Chat — web (internal/external), app-embedded, SMS, "
"Messenger, WhatsApp, Telegram, iMessage.",
"Website forms, mobile apps.",
),
),
SubTopic(
"inbound_reasons", "Inbound contact reasons",
(
"Top 35 inbound contact reasons and approximate % of calls.",
"Cost per call? Average Handle Time?",
"Busiest / least busy days? Seasonal variances?",
"Most difficult, commonly occurring calls? Easiest commonly "
"occurring call?",
),
),
SubTopic(
"outbound", "Outbound",
(
"Hours of operation.",
"Voice (preview / predictive dialer volume), email, SMS, "
"recorded announcement ports.",
"Self-service applications, live agent connect, campaign "
"management, DNC management.",
"Top 35 outbound contact reasons and approximate % of "
"calls.",
"After-call work?",
),
),
),
),
Topic(
key="agent_environment",
title="Agent & Supervisor Environment",
scope="Locations, endpoints, desktop, applications, knowledge",
minutes=10,
subtopics=(
SubTopic(
"locations_endpoints", "Locations & endpoints",
(
"Location types — WFH / offices.",
"Hard phone, soft phone, CODEC, wireless headset?",
"Agent greeting / pre-recorded messages, whisper "
"announcement.",
"PC — desktop, laptop, VDI.",
),
),
SubTopic(
"desktop_apps", "Desktop & applications",
(
"Agent & supervisor desktop — omnichannel? Custom gadgets, "
"screen pops, workflows.",
"Standard browser? SSO?",
"Applications used to handle calls.",
"Knowledge Management.",
),
),
),
),
Topic(
key="routing_automation",
title="Routing & Automation",
scope="Self-service, IVR, speech, virtual agents, agent assist, RPA",
minutes=15,
subtopics=(
SubTopic(
"self_service", "Self-service & IVR",
(
"IVR persona — branding, style guides, voice actors?",
"DTMF and/or speech? Speech recognition, TTS, NLU, voice "
"biometrics.",
"Self-service applications — ID & validate, deflection, "
"situational offer (outage / time of day / scheduled).",
"API integration (CRM). Intent capture, intent prediction, "
"offer push on prediction / account attribute.",
),
),
SubTopic(
"virtual_agents", "Virtual agents & assist",
(
"Virtual agents — which processes?",
"Agent assist?",
"RPA?",
"Current challenges or desired capabilities. Desire to "
"automate. DevOps team?",
),
),
SubTopic(
"digital_assistants", "Digital assistant apps",
(
"Alexa, Google Assistant, Siri?",
),
),
),
),
Topic(
key="workforce_engagement",
title="Workforce Engagement",
scope="Call recording / QM, WFM, agent self-service, integrations",
minutes=20,
subtopics=(
SubTopic(
"recording_qm", "Call recording & Quality Management",
(
"How is call recording used? Compliance, screen capture, "
"voice transcription (real-time?), desktop analytics, "
"retention period.",
"Quality team — who do they report to, how many people? "
"Scorecards, score method & metrics, number of assessments, "
"coaching, live monitor.",
"Locations with call recording. Number of named agents.",
),
),
SubTopic(
"workforce_management", "Workforce management",
(
"Recruitment process, required qualifications, average "
"tenure, attrition rate, internal moves.",
"Do you measure agent & supervisor experience? Recognition "
"program?",
"Adherence measure — KPIs, gamification, shift length, "
"breaks, annualized utilization %.",
"Forecasting & scheduling — peak volume, historical data, "
"algorithms, WFM interval (15/30 min).",
"Intraday / real-time adherence — what happens when out of "
"compliance?",
"Payroll integration (ADP / Workday). Satisfaction with "
"current tool(s)? Multiskilled agents, FTE calculations.",
),
),
SubTopic(
"agent_self_service", "Agent self-service & integrations",
(
"Agent self-service — absences, shift bids / swaps, "
"performance metrics.",
"Number of named agents.",
"Integration to 3rd party — outsourcer / overflow, payroll.",
),
),
),
),
Topic(
key="training",
title="Training",
scope="Onboarding, format, assessment, eLearning, QM integration",
minutes=5,
subtopics=(
SubTopic(
"onboarding", "Onboarding & enablement",
(
"Onboarding process — how long, training format, "
"assessment?",
"eLearning?",
"QM integration?",
),
),
),
),
Topic(
key="reporting_insights",
title="Reporting & Insights",
scope="Real-time & historical reporting, analytics, BI, CRM",
minutes=10,
subtopics=(
SubTopic(
"reporting", "Reporting",
(
"Real-time and historical — what are the key metrics you "
"report on?",
"Data source integration, dashboards, wallboards, agent & "
"supervisor status.",
),
),
SubTopic(
"analytics_insights", "Analytics & insights",
(
"Integrated view of customer details and contact history? "
"CRM?",
"Does the contact centre collect and use customer insight? "
"Predictive engagement?",
"What data analysis do you perform? Analytics / BI team — how "
"many people? BI platform?",
"Executive-level reporting? Marketing team interlock?",
),
),
),
),
)
# ── Lookups ──────────────────────────────────────────────────────────
TOPIC_BY_KEY: dict[str, Topic] = {t.key: t for t in TOPICS}
TOPIC_KEYS: tuple[str, ...] = tuple(t.key for t in TOPICS)
def topic(key: str) -> Topic:
"""Return the topic with ``key`` (raises ``KeyError`` if unknown)."""
return TOPIC_BY_KEY[key]

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

View File

@@ -0,0 +1,453 @@
Contact Center Exploration & Discovery Workshops
The Contact Center Discovery and Exploration workshops allow us to gain a clear perspective of your contact center operations. The discovery workshop is focused on developing an understanding of the current state architecture and IT support.
Ive attached a contact center survey to collect information and context in advance of the workshop and is also useful to develop business cases.
# CX Exploration
## Background
How many distinct lines of business are supported in the contact centre?
(eg, commercial, residential, retail, wholesale, etc)
Are you using contact center for internal Uses such as help desk, finance, HR, etc.?
What channels do you support?
Apps
Voice
Video
Chat
SMS
Email
Social Media
Digital Assistants
Payment card/PCI?
What are the availability SLAs or targets for your technology platform?
Mini org chart
Reporting structure
- Executive leader
What is the structure of decision making in their organization? Centralized or decentralized?
- Who are the key decision makers for implementing a plan for changes to the contact centre?
How important is CX & EX to your organization's strategy?
- Is there an executive that is accountable for CX? CXO, CDO?
Of your leading offers, what is the customer's top priority?
Competitive pressures?
Are their pending or recent acquisitions or spinoffs that require changes to their IT infrastructure and services?
What do they view as the problems in their contact centre today and what are the primary causes?
CX / Customer Success Leadership:
Are your contact centers managed by the same person?
- Managers:
- Team Leads:
- Agents:
Who carries the cost of contact centre agents and supervisors?
What revenue is generated by the contact center?
Do you have KPI targets for CX?:
CSAT:
NPS:
CES:
How are you doing?
Is there a VOC program in place?
• ROI/business value known?
• How do customers rate the experience they receive from your organization? 0-5
What are the key features of their corporate culture?
Is their a Voice of the Agent, or Employee satisfaction survey in place?
- How are they doing?
Automation strategy?
Any inflight projects?
- Any CX or EX improvement initiatives?
Decision
Channel management strategy?
Are your customer experiences personalized?
Do you have a clear set of design guidelines for CX?
Personas
Journey Mapping
Tools:
How are processes managed?
## CX Strategy
How is the value of Customer Experience defined within your organization?
- CX is a key BPI, recognized & measured as a financial value
Strategic Value
What revenue is generated by the contact center?
What are the key capabilities / services that are delivered by the contact centre?
Proposition
How are you using CX innovation to create market disruption?
How are competitors using CX to create competitive differentiation?
Organization Structure & Operating Model
Is there an executive that is accountable for CX? CXO, CDO?
Is there a CX team?
Do the CX insights team regularly educate the business
How are decisions made in the organization, is it centralized or decentralized?
- Who are the key decision makers for investment and changes to the contact centre'?
- Channel management strategy?
Who carries the cost of contact centre agents and supervisors?
Are they managed by the same person?
What are the teams?
How are processes managed?
Describe your automation strategy. Are there any desires or goals related to the contact centre?
- Who is your leader for Data & AI?
Are there any inflight projects that would impact the contact centre?
Are there recent or pending acquisitions or spinoffs?
Insight
How do you use analytics & data to generate a consolidated view of your customer experience?
Is there a VOC program in place?
• ROI/business value known?
• How do customers rate the experience they receive from your organization? 0-5
Approach
Continuous Improvement
How is customer insight used to drive CX improvement, loyalty and profitability?
How do you anticipate needs?
Do you have a clear set of CX design guidelines for CX?
Personas
Journey Mapping
Tools:
Do you have KPI targets for CX?:
CSAT:
NPS:
CES:
How are you doing?
Employee Engagement
Please describe you about your employee / Agent engagement strategy
How engaged are your people in delivering the customer experience?
Do you have a VoA/VoE program in place? How are you doing?
## Channels
May 6, 2025
2:52 PM
Inbound
Hours of operation
Who contacts the contact center? (Demographics, their situation)
Are certain callers or groups prioritized?
Languages?
English
Canadian French
Spanish
Video
Average number of active agents:
Voice
Average number of active agents:
Toll Free numbers & DIDs:
Approximate quantities or a list
Hours of operation? Any 24x7?
Average Wait Time:
Average Abandon rate:
Average Handle Time:
Average Call Hold Time:
Average After work call time:
Time to authenticate a caller:
% of calls transferred?
Internally?
Externally?
3rd parties handling certain types of calls, or being conferenced in?
Courtesy Callback/Virtual Hold
Post Call Survey
First Call Resolution Rate?
Average revenue per call (sales)?
Email, range of logged in users:
○ Response time:
○ Email server
Chat, range of logged in users:
Web Chat Internal
Web Chat External
App Integration / embedded
SMS
Facebook Messenger
WhatsApp
Telegram
iMessage
Web Site Forms
Mobile Apps
Top 3-5 Inbound contact reasons and approximate % of calls:
1.
Cost Per call?
Average Handle Time?
Busiest days:
Least busy days:
Seasonal variances?
What are your most difficult, commonly occurring calls?
What is the easiest commonly occurring call?
Outbound
Hours of operation
Voice, range of logged in users:
Preview, volume
Predictive dialer
Email, range of logged in users:
SMS, range of logged in users:
Recorded announcement, ports:
Self service applications
Transfer to agent
Live agent connect
Campaign management
DNC management
Top 3-5 outbound contact reasons and approximate % of calls:
1.
After call work?
## Agent & Supervisor Environment
Location types:
- WFH:
- Offices:
Hard phone
Soft phone
CODEC?
Headset, wireless?:
Agent greeting or pre-recorded messages
Whisper announcement
PC
Desktop
Laptop
VDI
Agent & Supervisor desktop (omnichannel?):
Custom gadgets
Screen pops
Workflows
Standard browser:
SSO:
Applications used to handle calls:
Knowledge Management:
## Routing & Automation
Self Service
IVR Persona?
Branding?
Style guides?
Voice actors?
DTMF
Speech
Speech recognition
Text To Speech
Natural Language Understanding
Voice Biometrics
Self service applications:
ID & Validate
Deflection
Situational Offer (Outage/ Time of Day / Scheduled)
API integration:
CRM
Intent Capture
Intent prediction
Offer push based on prediction/account attribute
Virtual Agents
Processes
Agent Assist
RPA
Current challenges or desired capabilities
Process management
Desire to automate
DevOps team?
Digital Assistant Apps
Alexa
Google Assistant
Siri
## Routing & Automation
Self Service
IVR Persona?
Branding?
Style guides?
Voice actors?
DTMF
Speech
Speech recognition
Text To Speech
Natural Language Understanding
Voice Biometrics
Self service applications:
ID & Validate
Deflection
Situational Offer (Outage/ Time of Day / Scheduled)
API integration:
CRM
Intent Capture
Intent prediction
Offer push based on prediction/account attribute
Agent Assist
RPA
Current challenges or desired capabilities
Process management
Desire to automate
DevOps team?
Digital Assistant Apps
Alexa
Google Assistant
Siri
Workforce Engagement
May 6, 2025
2:50 PM
Call Recording/QM
• How is call recording used?
Compliance
Screen capture
Voice transcription
Real time
Desktop analytics
Retention period
Quality Management
Do you have a quality team?
Who do they report to?
How many people work for the team?
Scorecards
Score method and metrics?
How many assessments are conducted?
Coaching
Live Monitor
• Locations with CR
• Number of Named Agents:
Workforce Engagement
• What is your recruitment process?
• What qualifications are required for the call center?
• What is the average staff tenure?
• What is the attrition rate?
• What proportion of the staff leave for other positions in the company per annum?
○ Are staff hired for the CC from other parts of the organization?
• Do you measure agent & supervisor experience?
○ How are they doing?
○ What type of recognition program do you have in place?
• Agent adherence measure?
○ KPIs
○ Gamification
○ How long is a shift?
○ What breaks are allocated
○ What annualized utilization % do you calculate?
• Forecasting & Scheduling
○ Peak call volume days, time of month, year?
○ Validate historical data
○ How are calculations performed (algorithms used)
○ WFM Interval (15/30 minutes)
• Intraday/ Realtime adherence
○ What happens when you are out of compliance, surprises happen?
• Payroll Integration
○ Payroll platform
• Satisfaction with current tool(s)?
○ Multiskilled agents
○ FTE Calculations
• Agent self-service?
○ How are absences reported?
○ Shift bids / swaps
○ Performance metrics
• Number of Named Agents:
• Integration to 3rd party
○ outsourcer / overflow:
○ Payroll: ADP / Workday
Training
• Onboarding process
○ How long is it?
○ Training format?
○ Assessment?
eLearning
QM Integration
## Reporting & Insights
Reporting
• Real time
• Historical
• What are the key metrics that you report on?
Data source integration
Dashboards
Wallboards
Agent & Supervisor status
Analytics & Insights
Do you have an integrated view of customer details and contact history?
CRM:
Does your contact centre collect and use customer insight?
Predictive engagement:
What sort of data analysis do you perform?
Do you have an analytics or business insights team?
How many people?
BI Platform:
What executive level reporting do you perform?
Marketing Team interlock

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "discoverylib"
version = "0.1.0"
description = "CX Exploration & Discovery Workshop — live facilitation aid (Mercury Notebook Pattern)"
requires-python = ">=3.10"
# The notebook is the deliverable (served with Mercury, exported via
# nbconvert, tables via tabulate) — the whole toolchain is a required
# runtime dependency, not an extra. `pip install -e .` must be enough.
dependencies = [
"pandas>=2.0",
"plotly>=5.18",
"mercury>=3.2",
"jupyterlab>=4.0",
"ipywidgets>=8.0",
"nbconvert>=7",
"tabulate>=0.9",
]
[project.optional-dependencies]
dev = ["pytest>=7.4", "mypy>=1.8"]
[tool.setuptools.packages.find]
include = ["discoverylib*"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
[tool.mypy]
strict = true
packages = ["discoverylib"]

View File

@@ -0,0 +1,362 @@
"""Generate notebooks/cx_discovery.ipynb from source cell text.
The discovery notebook has ~42 Mercury widgets (a status selector + a notes
box per topic, plus a checkbox per sub-topic). Hand-maintaining that JSON is
error-prone, so the notebook is *generated* from this script — the cell
sources live here as readable Python strings and nbformat writes valid JSON.
Re-run after editing any cell: python scripts/build_notebook.py
Then execute + export as usual (nbconvert / scripts/export_report.py).
This is a build tool, not the engine — all study logic stays in discoverylib.
"""
from __future__ import annotations
import pathlib
import nbformat as nbf
ROOT = pathlib.Path(__file__).resolve().parent.parent
OUT = ROOT / "notebooks" / "cx_discovery.ipynb"
# ── Cell sources ─────────────────────────────────────────────────────
MD_TITLE = """\
# CX Exploration & Discovery Workshop
The live visual for a discovery session. On screen the client sees the
**topic board** — each topic, its one-line scope, and a status glyph — the
**live sub-topic checklist** for whatever we're discussing now, and a
**progress headline** ("3/8 topics complete"). You drive the conversation
from the question script (which stays backstage); the client is never shown
a wall of questions.
**This notebook is the deliverable.** Serve it with
`mercury --working-dir .` and share that screen; mark each topic's status in
the sidebar as the discussion moves and tick sub-topics as you cover them —
the board and progress bar update live. Capture answers in the per-topic
notes boxes. Afterward, `python scripts/export_report.py` writes an
LLM-readable report source (notes + status + progress as markdown and JSON)
to feed the survey write-up or a downstream business-case study.
All content and logic live in `discoverylib/` — the notebook only arranges
and renders them.
Confidence legend: 🟢 confirmed · 🟡 estimated · 🔴 unknown — used in the
captured notes, not on the client-facing board."""
SETUP = '''\
# ── Setup ──────────────────────────────────────────────────────────
import sys, pathlib
_ROOT = pathlib.Path.cwd()
if not (_ROOT / "discoverylib").exists(): # notebook lives in notebooks/
_ROOT = _ROOT.parent
sys.path.insert(0, str(_ROOT))
import html as _html
import mercury as mr
# Single source of truth — the topic bank and all status/progress logic
# live in the library; only presentation (and Mercury widgets) lives here.
from discoverylib import (
TOPICS, STATUSES, STATUS_LABEL, STATUS_GLYPH, STATUS_COLOR,
build_session, subtopic_checklist, subtopic_id, session_json,
)
from discoverylib.staging import backstage
# ── Brand palette (docs/brand.md, light theme) ─────────────────────
NAVY, INK, MUTED = "#151d2c", "#2e404d", "#586671"
BLUE, GREEN, LINE = "#0072bc", "#00a34c", "#e2e6e9"
CARD_BG, HAIRLINE = "#f8f8f8", "#d5d9db"
FONT = "Georgia, 'Times New Roman', serif"
BODY_FONT = "Arial, 'Helvetica Neue', Helvetica, sans-serif"
def esc(s):
return _html.escape(str(s))
backstage(f"discoverylib loaded — {len(TOPICS)} topics · "
f"{sum(len(t.subtopics) for t in TOPICS)} sub-topics · "
f"{sum(t.prompt_count for t in TOPICS)} prompts")'''
MD_HOWTO = """\
## How to run this session
- **Sidebar** — one **status** selector and a **notes** box per topic, plus a
**sub-topic checkbox** for each thread. As the conversation moves, set the
topic you're on to *In progress*, tick sub-topics as you cover them, mark
the topic *Complete* (or *Skipped*) when you move on, and jot answers in its
notes box.
- **Stage** (this page) — the client-facing board and progress bar below
re-render on every change.
- **Backstage** (JupyterLab / the export) — the facilitator question script and
the captured-notes appendix. Neither shows on the Mercury stage."""
# The widget block is generated from the topic bank so it stays DRY and
# can never drift from discoverylib. Widgets ONLY — no other output
# (Mercury leaks stray widget-cell output into the sidebar).
WIDGETS = '''\
# ── Session controls (Mercury sidebar — widgets ONLY, no other output) ─
# Generated from the topic bank: per topic a status selector + notes box,
# per sub-topic a checkbox. Mercury re-runs only cells BELOW this one, so
# every .value is read in the next cell down — never here.
#
# _status_w[topic_key] -> Select (Not started / In progress / …)
# _notes_w[topic_key] -> TextInput (captured answers, backstage)
# _sub_w[(topic_key, sub)] -> CheckBox (covered?)
# Labels are distinct per widget, so Mercury's label-keyed widget cache
# never collides across topics/sub-topics.
_status_w, _notes_w, _sub_w = {}, {}, {}
for _t in TOPICS:
_status_w[_t.key] = mr.Select(
label=f"{_t.title} — status",
value=STATUS_LABEL[STATUSES[0]],
choices=[STATUS_LABEL[s] for s in STATUSES],
)
for _st in _t.subtopics:
_sub_w[(_t.key, _st.key)] = mr.CheckBox(
value=False, appearance="box",
label=f"{_t.title}: {_st.title}")
_notes_w[_t.key] = mr.TextInput(
label=f"{_t.title} — notes", value="")'''
STATE = '''\
# ── Session state (re-runs on any sidebar change) ───────────────────
# Read every widget .value and rebuild the session via the engine.
_LABEL_TO_STATUS = {STATUS_LABEL[s]: s for s in STATUSES}
STATUS_BY_TOPIC = {k: _LABEL_TO_STATUS.get(str(w.value), STATUSES[0])
for k, w in _status_w.items()}
NOTES_BY_TOPIC = {k: str(w.value) for k, w in _notes_w.items()}
DONE_SUBTOPICS = {subtopic_id(tk, sk)
for (tk, sk), w in _sub_w.items() if bool(w.value)}
SESSION = build_session(STATUS_BY_TOPIC, NOTES_BY_TOPIC, DONE_SUBTOPICS)
PROGRESS = SESSION["progress"]
# One curated line on stage; full echo backstage.
print(f"{PROGRESS.label} · {PROGRESS.resolved}/{PROGRESS.total} resolved · "
f"agenda ~{SESSION['agenda_minutes']} min")
backstage("status: " + ", ".join(f"{ts.key}={ts.status}" for ts in SESSION["topics"]))'''
# The client-facing board. Pure HTML string built from SESSION; rendered
# with mr.Markdown so it shows on the Mercury stage (and in exports).
BOARD = '''\
# ── Stage: the client-facing topic board + progress ─────────────────
def _progress_bar(frac, completed, total):
pct = max(0.0, min(1.0, frac)) * 100
return (
f'<div style="margin:6px 0 18px">'
f'<div style="height:12px;border-radius:6px;background:{LINE};'
f'overflow:hidden">'
f'<div style="height:100%;width:{pct:.1f}%;background:{GREEN};'
f'border-radius:6px;transition:width .3s"></div></div>'
f'<div style="font:13px {BODY_FONT};color:{MUTED};margin-top:6px">'
f'{completed} of {total} topics complete</div></div>')
def _topic_row(ts, is_active):
ring = f"2px solid {BLUE}" if is_active else f"1px solid {HAIRLINE}"
bg = "#eef5fb" if is_active else CARD_BG
active_tag = (f'<span style="font:600 12px {BODY_FONT};color:{BLUE};'
f'margin-left:8px">discussing now →</span>' if is_active else "")
sub = ""
if is_active and ts.subtopics_total:
items = []
for it in subtopic_checklist(_ACTIVE_TOPIC, DONE_SUBTOPICS):
mark = "" if it.done else ""
col = GREEN if it.done else MUTED
wt = "600" if it.done else "400"
items.append(
f'<li style="font:{wt} 14px {BODY_FONT};color:{col};'
f'margin:3px 0;list-style:none">'
f'<span style="display:inline-block;width:1.2em">{mark}</span>'
f'{esc(it.title)}</li>')
sub = (f'<ul style="margin:10px 0 2px;padding:0 0 0 34px">'
f'{"".join(items)}</ul>')
return (
f'<div style="border:{ring};border-radius:10px;background:{bg};'
f'padding:12px 16px;margin:8px 0">'
f'<div style="display:flex;align-items:baseline">'
f'<span style="font-size:18px;color:{ts.color};width:1.4em">{ts.glyph}</span>'
f'<span style="font:700 17px {FONT};color:{NAVY}">{esc(ts.title)}</span>'
f'{active_tag}'
f'<span style="margin-left:auto;font:12px {BODY_FONT};color:{MUTED}">'
f'{esc(ts.status_label)}</span></div>'
f'<div style="font:14px {BODY_FONT};color:{MUTED};margin:4px 0 0 34px">'
f'{esc(ts.scope)}</div>'
f'{sub}</div>')
_ACTIVE_TOPIC = SESSION["active_topic"]
_rows = "".join(_topic_row(ts, ts.key == SESSION["active_topic_key"])
for ts in SESSION["topics"])
_header = (
f'<div style="font:700 24px {FONT};color:{NAVY};margin:4px 0 2px">'
f'CX Discovery — topics</div>'
f'<div style="font:14px {BODY_FONT};color:{MUTED}">'
f'{len(SESSION["topics"])} topics · ~{SESSION["agenda_minutes"]} minutes</div>')
_board_html = (
f'<div style="max-width:760px">{_header}'
f'{_progress_bar(PROGRESS.fraction, PROGRESS.completed, PROGRESS.total)}'
f'{_rows}</div>')
# Assign to _ so the bare-expression repr doesn't render a second copy.
_ = mr.Markdown(text=_board_html)'''
MD_SCRIPT = """\
## Facilitator question script (backstage)
The prompts below render in JupyterLab and in the exports — **not** on the
Mercury stage. They are your running order; ask them conversationally and let
the topics expand or drop as the client answers. Tick each sub-topic in the
sidebar as you cover it."""
SCRIPT = '''\
# ── Facilitator question script — backstage only ────────────────────
# Renders in JupyterLab and the exports; hidden on the Mercury stage.
_lines = ["\\n# CX Discovery — facilitation script\\n"]
for _t in TOPICS:
_lines.append(f"\\n## {_t.title} · ~{_t.minutes} min")
_lines.append(f"_{_t.scope}_\\n")
for _st in _t.subtopics:
_lines.append(f"\\n**{_st.title}** — `{subtopic_id(_t.key, _st.key)}`")
for _p in _st.prompts:
_lines.append(f" - {_p}")
backstage("\\n".join(_lines))'''
MD_GATE = """\
## Verification & assertions
Engine pins use explicit values independent of the sidebar, so the gate tests
`discoverylib`, not the current session; structural ties hold at **any** widget
state. This cell must pass under headless `nbconvert --execute` — it is the
study's smoke test. Output renders backstage only."""
GATE = '''\
# ── Verification gate — must pass under headless nbconvert ───────────
def _assert(cond, msg):
assert cond, msg
# Engine shape — independent of widget state (Pattern §4)
_assert(len(TOPICS) == 8, "expected 8 topics")
_assert(sum(len(t.subtopics) for t in TOPICS) == 26, "expected 26 sub-topics")
_assert(SESSION["agenda_minutes"] == 110, "agenda minutes drifted")
_assert(set(STATUS_BY_TOPIC) == {t.key for t in TOPICS}, "status keys ≠ topics")
# Structural ties — hold at ANY sidebar setting
_p = SESSION["progress"]
_assert(_p.total == len(SESSION["topics"]) == 8, "progress total ≠ topic count")
_assert(_p.completed + _p.skipped + _p.in_progress + _p.not_started == _p.total,
"status counts don't sum to total")
_assert(0.0 <= _p.fraction <= 1.0, "fraction out of range")
_assert(_p.resolved == _p.completed + _p.skipped, "resolved identity broke")
for _ts in SESSION["topics"]:
_assert(0 <= _ts.subtopics_done <= _ts.subtopics_total, "sub-topic count out of range")
_assert(_ts.status in STATUSES, f"unknown status {_ts.status}")
# Export payload is plain-JSON serializable and consistent with the session
import json as _json
_payload = session_json(SESSION, meta={"note": "gate check"})
_json.dumps(_payload) # raises if not serializable
_assert(_payload["progress"]["completed"] == _p.completed, "export/session mismatch")
_assert(len(_payload["topics"]) == 8, "export lost a topic")
backstage("All assertions passed.")
backstage(f" {_p.label} · {_p.resolved}/{_p.total} resolved")'''
MD_APPENDIX = """\
## Data appendix — for the machines
The captured session as a markdown table plus one JSON block of state, so the
exported report is complete LLM input for drafting the survey write-up or
seeding a business-case study. Renders **backstage** — hidden on the Mercury
stage."""
APPENDIX = '''\
# ── Data appendix — LLM-readable dump of the captured session ───────
# Renders backstage only (JupyterLab / nbconvert exports).
import json as _json
# Session metadata — edit these live for the client, or leave as defaults.
_META = {
"client": "", # 🟡 fill in for the engagement
"date": "", # 🟡 workshop date
"facilitator": "", # 🟡
}
backstage("\\n#### Captured session\\n")
_rows = ["| Topic | Status | Sub-topics | Notes |",
"|---|---|---:|---|"]
for _ts in SESSION["topics"]:
_note = _ts.notes.replace("|", "\\\\|").replace("\\n", " ") or ""
_rows.append(f"| {_ts.title} | {_ts.status_label} | "
f"{_ts.subtopics_done}/{_ts.subtopics_total} | {_note} |")
backstage("\\n".join(_rows))
backstage(f"\\n{PROGRESS.label} · {PROGRESS.resolved}/{PROGRESS.total} resolved "
f"· agenda ~{SESSION['agenda_minutes']} min\\n")
backstage("\\n#### Session state (JSON)\\n")
backstage("```json")
backstage(_json.dumps(session_json(SESSION, meta=_META), indent=2, ensure_ascii=False))
backstage("```")'''
def md(source: str) -> nbf.NotebookNode:
return nbf.v4.new_markdown_cell(source)
def code(source: str) -> nbf.NotebookNode:
return nbf.v4.new_code_cell(source)
def build() -> nbf.NotebookNode:
nb = nbf.v4.new_notebook()
nb.cells = [
md(MD_TITLE),
code(SETUP),
md(MD_HOWTO),
code(WIDGETS),
code(STATE),
code(BOARD),
md(MD_SCRIPT),
code(SCRIPT),
md(MD_GATE),
code(GATE),
md(MD_APPENDIX),
code(APPENDIX),
]
nb.metadata = {
"kernelspec": {"display_name": "Python 3", "language": "python",
"name": "python3"},
"language_info": {"name": "python"},
}
return nb
def main() -> None:
OUT.parent.mkdir(parents=True, exist_ok=True)
nbf.write(build(), OUT)
print(f"wrote {OUT.relative_to(ROOT)} ({len(build().cells)} cells)")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,48 @@
"""Export the discovery notebook as an LLM-readable report source.
Executes the notebook fresh (widget defaults — or whatever you've captured and
saved in the notebook), then writes both formats to exports/:
exports/cx_discovery.html — human-reviewable
exports/cx_discovery.md — leanest LLM input
The client-facing board is HTML the export carries, but the machine payload —
every topic's status, sub-topic tally, and captured notes — lives in the
backstage data-appendix cell (markdown table + JSON), so the exported `.md` is
complete input for drafting the survey write-up or seeding a business case.
Run from the study root: python scripts/export_report.py
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
NOTEBOOKS = [
ROOT / "notebooks" / "cx_discovery.ipynb",
]
EXPORTS = ROOT / "exports"
def main() -> None:
picked = [nb for nb in NOTEBOOKS
if len(sys.argv) < 2 or sys.argv[1] in nb.name]
if not picked:
sys.exit(f"no notebook matches {sys.argv[1]!r}")
EXPORTS.mkdir(exist_ok=True)
for nb in picked:
for fmt in ("html", "markdown"):
subprocess.run(
[sys.executable, "-m", "nbconvert", "--execute",
"--to", fmt, "--output-dir", str(EXPORTS), str(nb)],
check=True, cwd=ROOT,
)
for p in sorted(EXPORTS.iterdir()):
if p.suffix in (".html", ".md"):
print(f"wrote {p.relative_to(ROOT)} ({p.stat().st_size / 1024:,.0f} KB)")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,7 @@
"""Make discoverylib importable even without the study venv active (the
normal setup is ``pip install -e ".[dev]"`` into the study-local ``.venv/``)."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))

View File

@@ -0,0 +1,117 @@
"""Session engine pins — status, progress, checklist, and export payload.
Progress and status are this study's "numbers"; these are the hand-checked
acceptance values the in-notebook gate re-pins (Pattern §4).
"""
from discoverylib import (
COMPLETE,
IN_PROGRESS,
NOT_STARTED,
SKIPPED,
TOPIC_KEYS,
active_topic_key,
build_session,
normalize_status,
progress,
session_json,
subtopic_checklist,
subtopic_id,
topic,
)
def test_normalize_status_defaults_unknown():
assert normalize_status("complete") == COMPLETE
assert normalize_status(None) == NOT_STARTED
assert normalize_status("garbage") == NOT_STARTED
def test_progress_all_not_started():
p = progress({})
assert p.total == 8
assert (p.completed, p.skipped, p.in_progress, p.not_started) == (0, 0, 0, 8)
assert p.fraction == 0.0
assert p.resolved == 0
assert p.label == "0/8 topics complete"
def test_progress_mixed_counts_and_fraction():
status = {
"background": COMPLETE,
"cx_strategy": COMPLETE,
"channels": IN_PROGRESS,
"agent_environment": SKIPPED,
# remaining four default to not_started
}
p = progress(status)
assert (p.completed, p.skipped, p.in_progress, p.not_started) == (2, 1, 1, 4)
assert p.resolved == 3 # complete + skipped
assert p.fraction == 2 / 8
assert p.label == "2/8 topics complete"
def test_active_topic_prefers_in_progress_then_first_open():
# in-progress wins even if a later topic is also in progress
assert active_topic_key({"channels": IN_PROGRESS}) == "channels"
# no in-progress → first not-started in canonical order
assert active_topic_key({"background": COMPLETE}) == "cx_strategy"
# everything resolved → None
all_done = {k: COMPLETE for k in TOPIC_KEYS}
assert active_topic_key(all_done) is None
def test_subtopic_checklist_marks_done():
t = topic("channels")
done = {subtopic_id("channels", "voice_metrics")}
items = subtopic_checklist(t, done)
assert len(items) == len(t.subtopics)
by_key = {i.key: i.done for i in items}
assert by_key["voice_metrics"] is True
assert by_key["inbound_context"] is False
def test_build_session_shape_and_subtopic_done_count():
status = {"channels": IN_PROGRESS, "background": COMPLETE}
notes = {"channels": " 6 channels; voice ~70% "}
done = {subtopic_id("channels", "voice_metrics"),
subtopic_id("channels", "outbound")}
s = build_session(status, notes, done)
assert len(s["topics"]) == 8
assert s["active_topic_key"] == "channels"
assert s["active_topic"].title == "Channels"
assert s["agenda_minutes"] == 110
ch = next(ts for ts in s["topics"] if ts.key == "channels")
assert ch.status == IN_PROGRESS
assert ch.subtopics_done == 2
assert ch.subtopics_total == len(topic("channels").subtopics)
assert ch.notes == "6 channels; voice ~70%" # trimmed
bg = next(ts for ts in s["topics"] if ts.key == "background")
assert bg.status == COMPLETE and bg.subtopics_done == 0
def test_session_json_is_plain_and_complete():
status = {"background": COMPLETE, "channels": IN_PROGRESS}
notes = {"background": "3 LOBs; PCI in scope"}
done = {subtopic_id("channels", "voice_metrics")}
payload = session_json(build_session(status, notes, done),
meta={"client": "Acme", "date": "2026-07-19"})
assert payload["study"] == "202607_CX_Discovery_Workshop"
assert payload["meta"]["client"] == "Acme"
assert payload["progress"]["completed"] == 1
assert payload["progress"]["fraction_complete"] == round(1 / 8, 4)
assert payload["active_topic"] == "channels"
assert len(payload["topics"]) == 8
bg = next(t for t in payload["topics"] if t["key"] == "background")
assert bg["status"] == COMPLETE
assert bg["notes"] == "3 LOBs; PCI in scope"
ch = next(t for t in payload["topics"] if t["key"] == "channels")
assert ch["subtopics_done"] == 1
# JSON-serializable (no dataclasses / sets leaked through)
import json
json.dumps(payload)

View File

@@ -0,0 +1,15 @@
"""Stage/backstage detection — Mercury kernels carry MERCURY_CONFIG_DIR."""
from discoverylib import staging
def test_backstage_prints_only_off_stage(monkeypatch, capsys):
monkeypatch.delenv("MERCURY_CONFIG_DIR", raising=False)
assert not staging.on_stage()
staging.backstage("visible")
assert capsys.readouterr().out == "visible\n"
monkeypatch.setenv("MERCURY_CONFIG_DIR", "/tmp/app")
assert staging.on_stage()
staging.backstage("hidden")
assert capsys.readouterr().out == ""

View File

@@ -0,0 +1,62 @@
"""Topic bank integrity — the verbatim facilitation record.
These pins are the anchor guard (Pattern §4): keys are stable identities
that captured notes and the JSON export key off, so renaming or reordering a
topic must be a deliberate, test-breaking act — never a silent drift.
"""
from discoverylib import TOPICS, TOPIC_KEYS, topic
from discoverylib.topics import TOPIC_BY_KEY
# ── Hand-checked shape (recount if you add/remove content) ───────────
def test_topic_count_and_order():
assert len(TOPICS) == 8
assert TOPIC_KEYS == (
"background",
"cx_strategy",
"channels",
"agent_environment",
"routing_automation",
"workforce_engagement",
"training",
"reporting_insights",
)
def test_subtopic_and_prompt_totals():
assert sum(len(t.subtopics) for t in TOPICS) == 26
assert sum(t.prompt_count for t in TOPICS) == 95
def test_agenda_minutes_sum():
from discoverylib import agenda_minutes
assert agenda_minutes() == 110
assert agenda_minutes() == sum(t.minutes for t in TOPICS)
# ── Structural invariants — hold for every topic ─────────────────────
def test_keys_unique_and_wellformed():
keys = [t.key for t in TOPICS]
assert len(keys) == len(set(keys)) # unique
for t in TOPICS:
assert t.key.replace("_", "").isalnum() # snake_case slug
assert t.title and t.scope # client-facing text present
assert t.minutes > 0
assert t.subtopics # no empty topic
sub_keys = [st.key for st in t.subtopics]
assert len(sub_keys) == len(set(sub_keys)) # unique within topic
for st in t.subtopics:
assert st.prompts # no empty sub-topic
def test_lookup_helpers():
assert topic("channels").title == "Channels"
assert TOPIC_BY_KEY["training"].minutes == 5
assert TOPICS[0].key == "background"
def test_no_double_dollar_or_raw_markup_in_scope():
# scope lines render on stage HTML — keep them plain text.
for t in TOPICS:
assert "<" not in t.scope and ">" not in t.scope