Chapter 1 · Sessions 1 and 2
What the old desk holds, and the tables that replace it
Before anything is built, you write down what the old help desk really does, from its own reports and bills. Then one prompt adds the module's fifteen tables to your Foundation schema, with the tests that prove the database refuses bad tickets, and you try them on the development project with made-up data.
25 min3 stepsSessions 1–2about 7 hours hands-on across six sessions
By the end of this chapter you can
- Inventory the old desk's channels, queues, service-level rules, figures and bills from its own pages, never from memory.
- Have Claude Code check the spine tables and write the fifteen svc_ tables, their rules and their tests in one pull request.
- Load the four hand-worked tickets as a test fixture and made-up data as the seed, and see both on the development project.
What this module replaces
M19 replaces help desk, IT service management and customer support subscriptions: Zendesk, Freshdesk and Freshservice, Jira Service Management, ServiceNow ITSM at small-business scale, Zoho Desk and Intercom [1][2]. It is one desk for three groups: customers who ask the business for help, employees who need a laptop or a password reset, and the people who look after plant IT and OT, the computers that run machines. Every table name starts with svc_.
| Capability | What it does | Tier | Built in these six sessions |
|---|---|---|---|
| Omnichannel intake | Email with threading, portal, phone logging, API; the requester matched to a person | MVP | Email, portal, phone and catalogue. Chat widget and Slack or Teams: written down, not built |
| Ticket workflow | Types, statuses, priority from impact and urgency, groups, assignment, internal notes, parent and child | MVP | Yes; merging tickets and assignment by skills are not built |
| SLA management | First response and resolution targets on business hours, holidays and pauses; breach warnings | MVP | Yes; next response is stored, not computed |
| Knowledge base | Internal and public articles with versions; suggestions while typing | MVP | Yes; the deflection rate needs portal sessions and is written down only |
| Service catalogue | Requestable items with forms (reusing the M01 form engine) | STD | One item, as an ordinary service request |
| Incident, problem, change | Major incident flag, problems with root cause, changes with plans and approval | STD | Yes |
| CMDB (IT and OT) | Configuration items including PLCs, HMIs and SCADA servers, with relationships | STD | Yes |
| CSAT and reporting | Surveys on resolve; first response, time to resolution, SLA attainment | STD | Yes |
| AI assist | Suggested category, summaries, replies, always approved by the agent | BIC | Not built |
Session 1: Inventory the old desk from its own reports and bills
60 minutesWhy
You cannot prove a replacement is as good as the old tool unless you wrote down, first, what the old tool does and what it reports. Session 6 compares your new figures with the numbers you copy today, so they must come from the tool's own reports and invoices, with the report's name beside each; a number from memory cannot be checked and will not survive the question "says who?".
Do this
Sit with whoever administers the help desk tool, with its settings and reports open. Tickets hold customers' names and messages: copy counts and settings, never ticket text. Open Claude Code in your repository:
cd ~/code/acme-platform && git switch main && git pull && claudeOn a new branch helpdesk/inventory, create docs/helpdesk-inventory.md as an empty form for me to fill in from our current help desk tool. Do not invent any figure, price, count or setting: every cell starts as "not yet read".
Sections, each a table:
1. Channels: channel (email, web form, chat, phone, Slack or Teams, walk-up, API, other), who watches it, usual first reply, where it is recorded.
2. Tools: name, owner, plan, agent seats, monthly or yearly bill, renewal date, export available (yes or no), source (invoice or account page, with its date).
3. Queues and service-level rules: queue, members, business hours and time zone, holiday list, first-reply target, resolution target, statuses that stop the clock, what happens on a breach.
4. The last four full weeks, from the tool's own reports: tickets created, tickets solved, first reply time, time to resolution, SLA attainment, satisfaction. For each: the report's name, the date range, and whether it counts business hours or calendar time.
5. Ten recent tickets classified (incident, service request, question, complaint), with a mark on any about plant equipment (PLC, HMI, SCADA, network). Counts only, no customer names or ticket text.
6. Equipment list and change approval today: where the IT and plant-floor equipment list lives, how a change is approved, whether there is a back-out plan, whether safety-related changes follow the plant's management-of-change (MOC) procedure.
7. What the export holds: tickets, comments, internal notes, users, organisations, articles, attachments, email message ids, time zone.
8. Workarounds people use today.
9. The first queue to replace, why, and its lead.
Add a line at the top: "Every number here comes from the tool's own pages or our invoices. Never estimate." Open a pull request titled "Help desk inventory" and show me the link. I will fill it in myself on GitHub.Then fill the form in on GitHub (open the file in the pull request, choose the pencil, edit, commit to the same branch), reading each figure from the tool's report pages and each price from an invoice. Take a ten-ticket export into a private folder outside the repository to fill in section 7, and delete it when the section is written.
You will see recreated screen
- Every figure has a column for where it came from. That column is what makes Session 6's comparison honest.
- The form is empty on purpose. If Claude Code offers "typical" figures, refuse them.
You will see recreated screen
| Week | Tickets solved | First reply (median) | SLA met |
|---|---|---|---|
| 1 | 41 | 1 h 52 m | 88% |
| 2 | 38 | 2 h 10 m | 84% |
| 3 | 44 | 1 h 41 m | 91% |
| 4 | 40 | 2 h 03 m | 85% |
- The date range: Session 6 compares the same days.
- Business or calendar time: the most common reason two tools disagree.
Check it worked
The pull request Help desk inventory has every section filled in, each figure with its report name and date range, each bill from an invoice with its renewal date, and the first queue chosen with a named lead who has read it. No customer name or ticket text appears anywhere. Owner two approves; merge.
Fastest path
Do sections 3 and 4 with the administrator in one sitting, screen shared: they are where most of the time goes, and both come from pages only an administrator can open.
If it goes wrong
Claude Code filled the form with typical figures or prices
Say: Replace every figure, price and count you wrote with "not yet read". I fill these in from our own reports and invoices. An invented number in an inventory is worse than a blank: nobody checks it later.
The tool does not report one of the measures
Write not reported in the cell, not an estimate. Session 6 then compares only what both tools report.
You cannot see the bill
Write who can (usually finance or IT) and ask them for the last invoice. Do not use the vendor's list price: your contract may differ.
The export has no email message ids or no internal notes
Write exactly what is missing in section 7. Session 5 handles both (replies thread by ticket number instead; missing notes are listed for the lead), but only if you know now.
The fifteen tables
Every table carries the standard columns id, site_id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext (extra data as JSON), and points at the tables docs/spine-map.md maps core_person, core_site and core_equipment onto (people, sites and equipment from the Foundation), so the desk keeps no people list, site list or equipment list of its own. site_id takes the place of the specification's tenant_id, so each table keeps one simple access rule. An arrow is a foreign key; soft link means a plain uuid with no foreign key, because the table it points at belongs to a module you may not have built (CRM, forms, content). req means required.
| Table | Holds | Columns (type; req = required) |
|---|---|---|
| svc_support_group | A team or queue | name text req, unique per site; email_alias text; business_hours_id → svc_business_hours; manager_id → core_person. Members are kept in ext.members |
| svc_business_hours | Working hours and holidays | name text req; timezone text req; schedule json req; holidays json |
| svc_sla_policy | SLA targets and conditions | name text req; conditions json req; first_response_min int; next_response_min int; resolution_min int; business_hours_id → svc_business_hours; pause_statuses json; priority_order int |
| svc_category | The category tree | name text req; parent_id → svc_category; default_group_id → svc_support_group |
| svc_ticket | A ticket | ticket_no text req, unique per site; ticket_type req (incident, service_request, question, problem, change, complaint, task); channel req (email, portal, chat, phone, slack, teams, api, walk_in); subject text req; description text; requester_person_id → core_person; requester_contact_ref soft link to crm_contact; account_ref soft link to crm_account; status req (new, open, pending_requester, pending_third_party, on_hold, resolved, closed); priority req (p1–p4); impact and urgency (low, medium, high); category_id; group_id; assignee_id → core_person; sla_policy_id; first_response_due_at, resolution_due_at, first_responded_at, resolved_at, closed_at timestamptz; parent_ticket_id → svc_ticket; problem_id; configuration_item_id; is_major_incident bool |
| svc_ticket_message | A public reply or internal note | ticket_id req; author_type req (agent, requester, system, ai); author_person_id → core_person; body text req; is_internal bool req; channel_message_id text, unique per site when present; sent_at timestamptz req |
| svc_sla_event | One metric on one ticket | ticket_id req; metric req (first_response, next_response, resolution), unique per ticket; target_at req; met_at; breached bool req; paused_minutes int |
| svc_catalog_item | A requestable service | name text req; description text; form_template_ref soft link to frm_template; approval_route json; fulfilment_group_id; sla_policy_id; active bool req |
| svc_problem | A problem or known error | problem_no text req, unique per site; title text req; root_cause text; workaround text; status req (open, investigating, known_error, resolved, closed); owner_id → core_person |
| svc_change_request | An IT or OT change | cr_no text req, unique per site; title text req; change_type req (standard, normal, emergency); risk req (low, medium, high); impact_analysis; implementation_plan; backout_plan; scheduled_start, scheduled_end; status req (draft, assess, authorize, scheduled, implementing, review, closed, failed, rejected); cab_decision_at; configuration_item_id |
| svc_configuration_item | An IT or OT item | ci_no text req, unique per site; ci_class req (server, workstation, laptop, network_device, application, database, plc, hmi, scada_server, historian, printer, mobile_device, cloud_service); name text req; status req (planned, in_service, maintenance, retired); owner_id; equipment_id → core_equipment; firmware_version; ip_address; attributes json |
| svc_ci_relationship | A dependency between items | from_ci_id req; to_ci_id req; relation req (depends_on, hosts, connects_to, part_of, backs_up). Never to itself; the same relation stored once |
| svc_kb_article | A knowledge article | title text req; body text req; visibility req (internal, public); status req (draft, published, retired); category_id; version int req; helpful_yes int; helpful_no int; cms_entry_ref soft link to cms_entry |
| svc_macro | A saved reply and set of actions | name text req; actions json req; group_id; active bool req |
| svc_csat_response | A satisfaction answer | ticket_id req, one per ticket; score int req; comment text; responded_at timestamptz req |
The database also keeps these rules, whatever writes to it: a ticket is never its own parent; an item never relates to itself; a change cannot reach authorize without both an implementation plan and a back-out plan; one svc_sla_event per ticket and metric; one svc_csat_response per ticket. The satisfaction scale is yours to choose and write down (1 to 5, with 4 and 5 positive, is an example). Ticket and change numbers come from core_number_sequence through a small numbering function, so no role needs the right to change the sequence table itself [3].
Session 2: Check the spine, then write the fifteen tables and their tests
40 minutesWhy
The module points at spine tables (core_person, core_site, core_equipment and a few helpers) that a Foundation schema built for the stamping plant may not have. Checking first, and adding anything missing in its own migration, keeps the module's migration small and keeps spine tables out of it. Writing the tables and the tests that try to break them in one pull request means the rules arrive already proven, and the schema check from Session 5 rebuilds everything from nothing before it can merge.
Do this
Read docs/naming-standard.md, docs/SCHEMA-PLAN.md and every file in supabase/migrations. Do not change anything yet.
Tell me which of our tables or functions plays each of these roles, and which are missing: core_person, core_site, core_equipment, core_job_role, core_attachment, core_action_item, core_number_sequence, core_comment (owner_type, owner_id, body, author_id), core_approval (owner_type, owner_id, step_no, role_required, approver_id, decision, comment, signature_id), core_audit_log with its trigger function core_audit_row() (records every insert, update and delete and refuses any change to the log itself), core_touch_row() (sets updated_at and updated_by and adds one to row_version). Where our Foundation tables already hold the same thing (sites, parts, lots, equipment, memberships), map the core_ name onto them; never a copy.
Then, on a new branch spine/helpdesk: add a section "M19 Help desk" to the one shared docs/spine-map.md (create it if no module has yet; never a separate help desk map): each core_ name and our table for it, and that the svc_ tables carry site_id (→ sites) in place of the specification's tenant_id. If anything is missing, add one migration (npx supabase migration new spine_for_helpdesk) with only what is missing, row-level security on and no policies, and pgTAP tests in supabase/tests/core.test.sql. Push, open a pull request titled "Spine for help desk", wait for every check to finish, and report the result in plain words. Then stop: I merge it before the module starts.When the spine is on main (or was already complete), give Claude Code the table list. First copy the table above into the repository so it can be read: the prompt asks Claude Code to write it from this lesson's text, which you paste after it.
On a new branch helpdesk/tables:
1. Create docs/svc-tables.md from the table list I paste below, exactly as written, plus three JSON shapes: svc_business_hours.schedule as opening periods per weekday, for example {"mon": [["09:00","17:00"]], ... "sat": [], "sun": []}; svc_business_hours.holidays as a list of dates; svc_sla_policy.pause_statuses as a list of ticket statuses. Write down that connects_to is always recorded from the item that uses the link to the item it talks to (the operator screen connects_to the PLC, never the reverse), and that a csat score is 1 to 5 with 4 and 5 counted as positive.
2. Run npx supabase migration new helpdesk_tables and write all fifteen svc_ tables in it, following docs/naming-standard.md:
- the standard columns in docs/spine-map.md on every table (id uuid, site_id not null references sites with an index, never tenant_id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb); timestamps as timestamptz;
- required means not null; allowed values are check constraints; foreign keys only to the tables docs/spine-map.md names, to sites and to each other; soft links (requester_contact_ref, account_ref, form_template_ref, cms_entry_ref) are plain uuid columns with no foreign key;
- unique per site: ticket_no, problem_no, cr_no, ci_no, svc_support_group.name, and svc_ticket_message.channel_message_id when present; one svc_sla_event per ticket and metric; one svc_csat_response per ticket;
- a ticket is never its own parent; a relationship never joins an item to itself and is stored once; a change cannot move to authorize without both implementation_plan and backout_plan;
- a status-change trigger on svc_ticket that writes an internal svc_ticket_message with author_type system and the old and new status in ext;
- numbering functions for ticket_no, problem_no, cr_no and ci_no from core_number_sequence, security definer with set search_path = '';
- core_touch_row() and core_audit_row() triggers on every table; row-level security enabled and forced on every table, with no policies yet.
3. Add the fifteen tables to docs/matrix.json as rows with every cell empty (Session 3 fills them), so the policy generator knows they exist.
4. Write pgTAP tests in supabase/tests/helpdesk.test.sql proving: every svc_ table exists with row-level security on and forced; each allowed-value list refuses one wrong value (including ticket_type 'bug'); a change moved to authorize with no back-out plan is refused; an item related to itself is refused; a second csat answer for the same ticket is refused; the same channel_message_id twice is refused; and a status change writes one system note.
5. Do not connect to any Supabase project.
Push, open a pull request titled "Help desk tables", wait for every check to finish, and tell me the result in plain words, with how many tests ran. If a check fails, fix it and wait again before reporting.
The table list:
<paste the table "The fifteen tables" from element M19 here>You will see recreated screen
- The migration's name starts with the date and time, so it always runs after the spine migration.
- A rule in the table itself: no plan, no authorisation, whoever writes the row.
- The summary counts the refusals. Check the same numbers in the pull request's checks tab before you believe them.
Check it worked
The M19 section is in docs/spine-map.md on main. Pull request Help desk tables is green on its latest commit, the checks tab shows the schema test passing, docs/svc-tables.md holds the table list and the three JSON shapes, and owner two has approved. Merge: the deploy workflow from Session 11 applies the migration to production.
Fastest path
Paste the table list into the same prompt rather than describing it: Claude Code then builds from the exact columns and allowed values, and you skip the round of "you missed walk_in" corrections.
If it goes wrong
CI fails with "column does not exist" or a table missing on the fresh database
A table was created by hand somewhere, or a change has no migration. Say: Rebuild from nothing with only the files in supabase/migrations and tell me which object no migration creates. Write the missing migration as a new file, never by editing an old one. We merged a change that added ten columns with no migration; it worked on one machine and failed everywhere else.
Claude Code put core_ tables inside the module's migration
Say: Move every core_ table into a separate spine migration on its own branch. The module's migration creates only svc_ tables. Spine tables are shared by every module; they must not depend on this one.
Claude Code adds tenant_id, or writes the mapping into docs/svc-tables.md
Say: The svc_ tables carry site_id, never tenant_id, and the mapping lives only in the M19 section of docs/spine-map.md. One map for every module means the next module finds the same answer.
The tests pass but the summary's numbers differ from the checks tab
Trust the checks tab. Say: Show me the exact command you ran, its exit code and the last 20 lines of its output. A summary is a claim; the check on GitHub is the evidence.
After merging main into the branch, a column or test you added has gone
Someone undid a batch on main and the undo took yours with it, with no conflict. Say: I just merged main. List every schema change and test this branch added and confirm each is still there. If any disappeared, find the commit that removed it and tell me before changing anything.
Four tickets worked by hand
The service-level clock in Session 4 must give exactly the answers you work out today, so the tickets it is tested on are worked by hand first. They use fixed dates because the arithmetic needs known weekends and a known holiday, which is why they are a test fixture, not the seed. The seed, supabase/seeds/helpdesk.sql, is made-up data shifted onto today, so the screens never go blank as it ages. The lab values below are for practice, not recommendations.
| Setting | Lab value |
|---|---|
| Business hours | Monday to Friday, 09:00 to 17:00, in your plant's time zone |
| Holiday | Monday 2026-05-25 |
| Policy for priority p3 | first response 240 minutes, next response 240, resolution 960 (16 business hours) |
| Pause statuses | pending_requester, pending_third_party, on_hold |
| Ticket | Created | First reply | First reply due | Resolution due | Resolved | Result |
|---|---|---|---|---|---|---|
| A | Tue 05-19 10:00 | 11:00 | Tue 14:00 | Thu 05-21 10:00 | Thu 11:30 | Resolution breached by 90 minutes |
| B | Fri 05-22 15:00 | Tue 05-26 10:00 | Tue 05-26 11:00 | Wed 05-27 15:00 | Wed 14:00 | Met |
| C | Sat 05-23 11:00 (starts Tue 09:00) | Tue 12:00 | Tue 05-26 13:00 | Wed 05-27 17:00 | Wed 16:00 | Met |
| D | Tue 05-19 10:00 | 11:00 | Tue 14:00 | Thu 05-21 14:00 (240 minutes paused) | Thu 13:30 | Met |
| E (extra case) | Wed 05-20 16:30 | 16:45 | Thu 05-21 12:30 | Fri 05-22 16:30; with a pause Thu 10:00–12:00, Tue 05-26 10:30 | Kept out of the four-ticket figures |
Session 2: The worked tickets as a fixture, made-up data as the seed, and a look on the development project
35 minutesWhy
The clock test needs fixed answers you trust, and the screens need data that looks like this week. Keeping the two apart stops the commonest seed fault: fixed dates that age until every "due today" panel is empty. Writing the seed's counts down, with a test that checks them, stops the second: a later step that says "you should see 6 open tickets" when the seed made 4. Then you, not Claude Code, apply the migration to the development project and look at it.
Do this
On a new branch helpdesk/seed:
1. Write tests/fixtures/helpdesk-clock-cases.json holding the lab business hours (Mon–Fri 09:00–17:00 in our plant's time zone, holiday 2026-05-25), the p3 policy (240, 240, 960, pause statuses pending_requester, pending_third_party, on_hold) and tickets A to E with every input and every expected value exactly as in the table I paste below. These are worked by hand: never change an expected value to make a test pass.
2. Write supabase/seeds/helpdesk.sql and list it under [db.seed] sql_paths in supabase/config.toml (never append to supabase/seed.sql), following the Foundation seed's rules: the syn site, every timestamp shifted onto today (read the clock once at seeding and keep every gap), every visible name starting "SYNTHETIC · ", safe to run twice (on conflict do nothing on every number and unique key): two support groups (Service desk, Plant IT and OT) each with two members in ext.members; business hours and one p3 policy as above; three categories; 12 tickets across the last 10 working days in every status, two of them about the PLC; their messages, public and internal; four configuration items (a PLC linked to a press in core_equipment, its HMI, a SCADA server and a network switch) with relationships (the HMI and SCADA server connects_to the PLC, the PLC depends_on the switch); one draft change request for a PLC firmware update with both plans; one problem; two draft knowledge articles; one macro.
3. Write docs/svc-seed-counts.md listing every count the seed makes, and a pgTAP test in supabase/tests/helpdesk-seed.test.sql that runs after the seed and asserts each count, that running the seed a second time changes no count, and that the newest seeded ticket is less than one day old.
Push, open a pull request titled "Help desk seed and clock cases", wait for the checks, and report in plain words.
The worked tickets:
<paste the table "Four tickets worked by hand" from element M19 here>When it is merged, apply the module and its made-up data to the development project yourself, in a terminal (not inside Claude Code). The first time, --include-seed loads every seed file listed in config.toml, helpdesk.sql included; after that, npm run seed:dev reloads them. Production gets the migration from the deploy workflow, which never seeds it. The password is the development project's, from the password manager.
cd ~/code/acme-platform && git switch main && git pullnpx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase db push --include-seedhttps://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
The development project's Table Editor. Check the project name at the top says acme-platform-dev.
You will see recreated screen
- The reference is the development project's (tsrqponmlkjihgfedcba). If it shows abcdefghijklmnopqrst, stop: that is production.
- One file, the one you just merged. If it lists files you do not expect, answer n and ask why.
You will see recreated screen
| ticket_no | subject | status | priority | created_at |
|---|---|---|---|---|
| T-000012 | SYNTHETIC · HMI on press 3 frozen | open | p2 | today 08:14 |
| T-000011 | SYNTHETIC · New starter laptop | pending_requester | p3 | yesterday 14:02 |
| T-000010 | SYNTHETIC · Label printer offline | resolved | p3 | 2 days ago |
- Expected until Session 3 generates the access rules.
- Names say SYNTHETIC; dates are relative to today, so this view still looks current next month.
Check it worked
On the development project, npx supabase migration list shows the same migrations under Local and Remote; the Table Editor shows twelve SYNTHETIC tickets dated within the last two weeks; the seed-count test is green on main.
Fastest path
Later, after any change to the seed, run npm run seed:dev yourself instead of pushing again; never reset the development project. Put both the fixture and the seed in one pull request, as the prompt does: they are checked by the same CI run, and the counts file is written while the seed is fresh in Claude Code's context.
If it goes wrong
db push asks to apply migrations to production (abcdefghijklmnopqrst)
Answer n. You are linked to the live project. Run npx supabase link --project-ref tsrqponmlkjihgfedcba and try again. Production gets migrations only from the deploy workflow on merge.
"Remote migration versions not found in local migrations directory"
Someone changed the development project outside the files. Do not force anything. In Claude Code: db push on the development project says remote versions are not in the local directory. Explain which versions differ and what each did, without changing any project.
A week later the seeded screens show nothing due today
The seed has fixed dates. Say: Change the seed so every timestamp moves by one offset that makes the newest record the moment of seeding, read the clock once, and keep every gap between related rows. Add a test that the newest ticket is less than one day old. Our seeded data was 10.9 days old eleven days later, and every "recent" panel was empty.
A later check expects a count the seed does not make
Fix the seed, not the check, then reload it with npm run seed:dev. Say: List every count any later step or test expects, and show the seed line that makes each. Anything with no line: fix the seed. Reviews of five Academy modules found this fault.
The seed fails with "permission denied for table core_number_sequence"
The numbering function is not security definer, or it was created without set search_path = ''. Say: Write a new migration that makes the numbering functions security definer with set search_path = '', with a test.
Knowledge check
Where should the four hand-worked tickets with fixed May dates live?
Knowledge check
Why is svc_ticket.requester_contact_ref a soft link while svc_ticket.group_id is a foreign key?
References
- Atlassian: Jira Service Management ITSM features. https://www.atlassian.com/software/jira/service-management/features/itsm
- Freshworks: Freshservice IT service desk. https://www.freshworks.com/freshservice/it-service-desk/
- PostgreSQL Documentation: Constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
- Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
Chapter 2 · Session 3
Who may do what, and the three screens
Access is decided once, in the role matrix, and the database rules, the sign-in guard and the menus are generated from it. This chapter adds the desk's five roles and three machine logins to the matrix, checks every later step against it before it is needed, and builds the portal, the agent queue and the lead view.
25 min3 stepsSession 35 roles, 3 machine logins
By the end of this chapter you can
- Write the desk's roles and machine logins into docs/matrix.json and regenerate the access rules and the route list from it.
- Walk every operation Sessions 4 to 6 will need and find the missing rights now, not when a step is refused.
- Build the requester portal, the agent queue and the lead view, and try them as each demo login on a phone.
Five roles and three machine logins
Roles are jobs, not people. Three of the desk's writers are not people at all: the intake route that receives email and portal requests, the service clock that sets due times, and the import login that brings in the old tool's history. Each gets its own database login and its own rows in the matrix, never the project's service key, which skips every access rule [1]. Nobody gets delete.
| Role or login | Reads | Writes | Never |
|---|---|---|---|
| Requester | Own tickets; public messages on them; published public articles; active catalogue items; categories | Nothing directly: every request goes through the intake route | Internal notes; anyone else's ticket |
| Agent | Every ticket, message (internal too), SLA event, group, category, macro, policy, problem, change, item, article | Tickets in own groups (status, priority, impact, urgency, category, group, assignee, parent, problem, item); replies and notes; problems; changes they created; draft articles | is_major_incident, the due times, first_responded_at, resolved_at, closed_at; another group's tickets |
| Support lead | Everything, including every draft article and the whole desk's figures | Everything an agent can, in every group; groups, hours, policies, categories, catalogue, macros; the major incident flag; publishing articles; items and relationships | Delete anything |
| Change approver | Changes, items, relationships, problems; tickets that point at an item | A change from authorize to scheduled or rejected, with cab_decision_at and a core_approval row | Approve a change they created |
| CI owner | Own items and their relationships; changes and tickets on them | Own items (status, firmware_version, ip_address, attributes, equipment_id); relationships from them; comments | Another owner's item |
| Intake route (login) | People, groups, categories, catalogue, tickets, messages, published public articles | New tickets and requester or system messages; routing at creation; reopening on a reply; one survey answer | Internal notes; the clock's columns |
| Service clock (login) | Tickets, messages, policies, hours, groups, SLA events, the requester's address | SLA events (insert and update: an upsert needs the read right too); the due and done times; resolved to closed; breach warnings in core_action_item | Reply to anyone |
| Import login (insert-only) | People, groups, categories, policies, tickets, messages, articles | Inserts only: external people, tickets, messages, draft articles, each with a legacy key; set to NOLOGIN at cut-over | Update or delete anything; SLA events, change requests |
Session 3: Put the roles in the matrix, walk every later step, and generate the rules
35 minutesWhy
Every access rule, route guard and menu is generated from docs/matrix.json, so a right that is missing there is refused later, in the middle of the workflow, and the temptation is to widen a rule by hand. Walking every operation Sessions 4 to 6 will ask for, now, and writing the cell that allows each, finds those gaps while they cost one line. The generated tests then prove each role is allowed what it needs and refused what it must not have.
Do this
Read docs/matrix.json, scripts/gen-policies.mjs, docs/access-review.md, docs/svc-tables.md and supabase/tests/access.test.sql. On a new branch helpdesk/access:
1. Add to docs/matrix.json the roles requester, agent, support_lead, change_approver and ci_owner, and the machine logins svc_intake, svc_clock and svc_import, with the cells I paste below. Nobody gets delete. No read rule filters on archived_at.
2. Write docs/svc-operations.md: walk Sessions 4, 5 and 6 of the help desk module (intake and threading, routing and macros, the SLA clock and its warnings, resolve and survey, major incident, problem, knowledge, change with the CMDB impact query, catalogue request, the import and its re-run, the lead's report) and write one line per read, insert or update: role or login, operation, table, and the matrix cell that allows it. List every line with no cell at the top under "Gaps" and stop to show me the gaps before going on.Read the gaps with the support lead. The usual ones: the clock reading svc_sla_event (its upserts need it), core_action_item for the clock and the lead, core_approval and core_comment for the approver, core_attachment for the intake route, core_person for the import login. Agree each, then:
Add the cells for the gaps we agreed. Then:
3. Run node scripts/gen-policies.mjs to generate the new policy migration (never a hand-written policy), and regenerate the access tests, so there is one allowed and one refused test per cell plus the cross-site test.
4. In a separate migration (npx supabase migration new helpdesk_logins), create the database logins svc_intake, svc_clock and svc_import with NOLOGIN for now, no BYPASSRLS, and not owners of any table. I set their passwords myself later.
5. Add triggers that refuse the column limits row rules cannot express: an agent changing is_major_incident, a due time, first_responded_at, resolved_at or closed_at; the intake route writing an internal note; the import login updating any row (it is insert-only).
6. Add pgTAP tests: a requester cannot read another requester's ticket or any internal note; an agent in the other group cannot update this group's tickets; an agent cannot set is_major_incident or a due time; nobody approves a change they created; a CI owner cannot update another owner's item; svc_import cannot insert svc_sla_event or svc_change_request, and cannot update any row; and a test that runs every line of docs/svc-operations.md as its role against the seed and checks it is allowed and the row really changed.
Update docs/access-review.md. Push, open a pull request titled "Help desk access", wait for every check, and report in plain words with the counts of allowed and refused tests.You will see recreated screen
- The walk finds the missing rights before any step needs them.
- The rules are generated from the matrix, never written by hand.
- "Really changed" matters: an update a role cannot read reports success and changes nothing.
Check it worked
Pull request Help desk access is green; docs/svc-operations.md has no line under Gaps; docs/access-review.md shows a row for each new role and login; no policy in the generated migration allows delete.
Fastest path
Paste all the cells at once (the role table above is written as cells) instead of adding roles one by one: the generator runs once and the tests cover everything in one CI run.
If it goes wrong
The clock's update "succeeds" but the row does not change
An update only finds rows the login can read. Say: Check that svc_clock's read rule on svc_sla_event covers the row before and after the change, and that inserts returning the new row have a read right. Add a test per role that checks the row really changed. We hit this in three modules.
The generator refuses: a table is missing from the matrix
That refusal is the protection working. Say: Add the missing table to docs/matrix.json with empty cells, then run the generator again. Never switch the check off.
Claude Code added a delete right, or edited a generated policy by hand
Say: Remove it. Rights come only from docs/matrix.json through scripts/gen-policies.mjs, and nobody has delete on records. Then read the Files changed tab: the generated migration must be the only policy file that changed.
Tests pass in the SQL editor, but the app still shows another group's tickets
The app connects as a login that skips the rules (the owner or the service key). Say: Confirm row-level security is forced on every svc_ table and that the app and the three machine logins are not owners and have no BYPASSRLS. Prove it with a test as each login.
The three surfaces
| Screen | For | Shows |
|---|---|---|
| /support, /support/new, /support/t/[ticket_no] | Requester | My requests; a form that offers published articles as the person types, and the catalogue; one ticket with public messages only and a reply box |
| /desk, /desk/t/[ticket_no] | Agent | Open tickets sorted by due time, with a badge in words (due in 40 minutes, breached, paused), never colour alone; the thread with an internal-note switch and a macro menu |
| /desk/changes, /desk/cis | Agent, approver, CI owner | Changes with their gates; configuration items and their relationships |
| /desk/lead | Support lead | Tickets at risk, breached and unassigned; each group's load; the report panel (Session 6) |
Session 3: Build the portal, the agent queue and the lead view
30 minutesWhy
The screens are where people decide whether the new desk is better than the old one. Building them against the seed, with the access rules already in place, means each screen shows only what its role may see from the first day. Generating the new addresses from the matrix keeps the sign-in guard from Session 9 denying everything it was not told about, and the phone check matters because requesters and plant engineers work on phones.
Do this
Before writing any page, read the routing and proxy guides in node_modules/next/dist/docs/ (this Next.js version differs from older guides; request checks live in proxy.ts) and lib/access/routes.ts.
On a new branch helpdesk/screens:
1. Add the screens /support, /support/new, /support/t/[ticket_no], /desk, /desk/t/[ticket_no], /desk/changes, /desk/cis and /desk/lead to the screens section of docs/matrix.json with the roles that may open each, and regenerate lib/access/routes.ts with node scripts/gen-routes.mjs, as Session 9 does. Do not edit proxy.ts or routes.ts by hand.
2. Build the pages against the seed, as described in element M19 chapter 2: the badge on /desk says the due state in words, never colour alone; an empty list or an unknown figure shows "No data", never 0; the person on every record comes from the signed-in session on the server, never from the page.
3. Follow the Foundation operator-screen rules: 44 px tap targets, 16 px form fields, 15 px body text, no sideways scrolling at 360 and 390 px, contrast at least 4.5:1.
4. Add screen tests at phone size: signed out, every page lands on sign-in; as each role, the pages it may open load and the others are refused; the requester sees only their own tickets and no internal note.
Push, open a pull request titled "Help desk screens", wait for every check and the Vercel preview, and give me the preview address and the result in plain words.You will see recreated screen
- If it does not read the guides, stop it and say: read node_modules/next/dist/docs/ first.
- Open the preview yourself: the check is what you see on a phone, not the summary.
You will see recreated screen
- The due state is a sentence, so it reads without colour and on a sunlit phone.
- Breached is said in words, with how long ago.
Check it worked
On the preview, signed out, every desk page sends you to sign-in. Signed in as each role on your phone, each page loads, nothing scrolls sideways, and the requester sees no internal note. The screen tests are green.
If it goes wrong
A link opens a blank 404, or a page appears with no styling
Test by visiting, not by compiling. Say: Start the production build locally, sign in as each role, visit every page and every link on it, and report every 404, error page, unstyled page and console error. We once had 130 tool links that type-checked and went nowhere.
Every record says it was created by the same person
The page is sending the user's identity. Say: Make the server take the person from the signed-in session and ignore what the page sends. Add a test that creates a record as two different users and checks the author.
A screen shows 0 where there is no data
Say: Show "No data" for any figure with nothing measured behind it, never 0, and add a test that renders each panel with an empty database. A zero is a real reading; an empty panel is not one.
Claude Code wrote middleware.ts, or edited proxy.ts by hand
Say: This Next.js uses proxy.ts, and its rules come from lib/access/routes.ts generated from docs/matrix.json. Remove the hand edit and regenerate.
Session 3: Demo logins on the development project, and a trial with the lead
25 minutesWhy
Tests prove the rules; people prove the screens. One demo login per role on the development project lets you and the support lead use the desk exactly as each role will, without real data and without inviting anyone. Ten silent minutes watching the lead and one requester try it find the confusing screens before the workflow is built on them.
Do this
Create seven users on the development project with Add user, then Create new user (not invite): requester.test@example.com, requester2.test@example.com, agent.test@example.com, agent2.test@example.com, lead.test@example.com, approver.test@example.com and ciowner.test@example.com. Generate each password in the password manager and save it there; tick Auto confirm user.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/auth/users
Authentication, Users, on the development project. Check the name at the top says acme-platform-dev.
Write supabase/snippets/svc-demo-logins.sql for me to run in the development project's SQL editor. Do not run it. It finds the seven demo users by email in auth.users and gives each a membership and a core_person row: requester.test is the requester on half the seeded tickets and requester2.test on the rest; agent.test is in Service desk and agent2.test in Plant IT and OT (ext.members); lead.test is support_lead; approver.test is change_approver; ciowner.test is ci_owner and owner_id of the PLC item; the seeded change request was created by agent.test. It must refuse to run if the database holds any row not marked SYNTHETIC in svc_ticket. Open a pull request titled "Help desk demo logins" and wait for the checks.After it merges, copy the file from GitHub into the development SQL editor and run it. Then sign in on the preview as each demo login. Finally sit the support lead in front of /desk/lead and one requester in front of /support on their own phone. Do not explain anything; write down where each one stops or asks.
You will see recreated screen
- Generated and saved in the password manager first; never in a file or a chat.
- Without it the user waits for a confirmation email that example.com never receives.
Check it worked
Each of the seven demo logins signs in on the preview and sees exactly its role's pages. You have a written note of where the lead and the requester stopped, and each note is either fixed or written down as a decision.
If it goes wrong
The page says "check your email" and nothing arrives
You used Invite, and example.com addresses receive nothing. Delete the user and create it with Create new user and Auto confirm user. If a real invite to a real address says sent and never arrives, the sending is failing: Session 9's honest-email check should say why in the logs.
requester.test sees requester2's tickets
Stop. The access rules are wrong, not the screen. Say: requester.test can read another requester's ticket on the development project. Find the rule that allows it, fix it in docs/matrix.json, regenerate, and add the failing case as a test.
The snippet refuses to run because of rows not marked SYNTHETIC
Good: it found real data. Check which project you are in. Real data never goes into the development project without IT's written approval (Session 5).
Knowledge check
The service clock's update to svc_sla_event reports success but nothing changes. What is the likely cause?
Knowledge check
Who sets requester_person_id when a request comes in through the portal?
References
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- PostgreSQL Documentation: Row Security Policies. https://www.postgresql.org/docs/current/ddl-rowsecurity.html
- W3C: Web Content Accessibility Guidelines (WCAG) 2.2. https://www.w3.org/TR/WCAG22/
Chapter 3 · Session 4
The workflow: intake, the clock, incident, problem and change
One session builds the desk's working day: email and portal requests become tickets and replies join them; the service-level clock counts only business time; a resolved ticket needs a reply and gets a survey; and incidents, problems and changes on PLCs follow ITIL 4 with the plant's own change control. You type the keys; Claude Code builds and proves the rest.
30 min4 stepsSession 4the keys typed by you
By the end of this chapter you can
- Set the machine logins' passwords and the route secrets yourself, and list them by name in docs/KEYS.md.
- Have Claude Code build intake with threading, and the service-level clock with its test matrix written first.
- Run resolve and survey, a major incident, a problem and a PLC change through their gates as the demo logins.
The keys this module adds
Three things in this module need secrets: the two machine logins the website uses, the secret your mail host sends with each forwarded email, and the key that signs survey links. Each is made and typed by you into the place that uses it. Claude Code never sees one; docs/KEYS.md lists them by name only.
| Key or secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| svc_intake and svc_clock passwords | The database logins the intake route and the clock use | Password manager; set in each project's SQL editor; inside the connection string in Vercel | Owner one and owner two | Pasted into Claude Code, a chat or a file |
| SVC_INTAKE_DATABASE_URL, SVC_CLOCK_DATABASE_URL | Connections for those logins (Preview: the development project; Production: the live one) | Vercel environment variables | Owners | Committed, or used in the browser |
| SVC_INBOUND_SECRET | Proves a forwarded email came from your mail host | Vercel environment variable and the mail host's forwarding setting | Owners | Sent in a URL, logged, or shown on a page |
| SVC_SURVEY_SIGNING_KEY | Signs single-use survey links | Vercel environment variable | Owners | Shared between environments |
| SVC_EMAIL_MODE (not secret) | off, test (your own addresses only) or on | Vercel environment variable | Owners | Set to on before Session 6's cutover |
Session 4: Set the logins' passwords and the route secrets yourself
20 minutesWhy
The intake route and the clock must write with their own narrow logins, not the service key that skips every rule, and those logins need passwords. The forwarded-email address must refuse anyone who is not your mail host. All of these are secrets, so a person makes and types them into the service that uses them: nothing in the repository, no chat, no prompt. Doing it before the code exists means the code is tested against the real arrangement from its first run.
Do this
Generate two random values in your own terminal, one at a time, and save each straight into the password manager (entries acme-platform: SVC_INBOUND_SECRET and acme-platform: SVC_SURVEY_SIGNING_KEY):
openssl rand -hex 32Generate two database passwords in the password manager (svc_intake, svc_clock; letters and digits only, so they need no encoding in an address). In the development project's SQL editor, type each one in place of the angle brackets and run:
alter role svc_intake with login password '<from the password manager>';
alter role svc_clock with login password '<from the password manager>';https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
Development SQL editor. Repeat on the live project (acme-platform-prod) with different passwords once the access migration has been deployed there.
Then add the variables in Vercel. For each database login, use the connection string from the project's Connect panel (the pooler address it recommends for Vercel), with the user name svc_intake.tsrqponmlkjihgfedcba (or svc_clock.…) and that login's password. Preview gets the development project's, Production the live one's. Paste values only, with no NAME= and no quotes. Set SVC_EMAIL_MODE to off in both.
https://vercel.com/acme-ops/acme-platform/settings/environment-variables
Vercel: Settings, Environment Variables.
Add to docs/KEYS.md, by name only, with what each unlocks, where it lives and who holds it: SVC_INTAKE_DATABASE_URL, SVC_CLOCK_DATABASE_URL, SVC_INBOUND_SECRET, SVC_SURVEY_SIGNING_KEY and SVC_EMAIL_MODE (not secret: off, test or on). Add them to the start-up check from Session 10 so a missing or malformed one is named in the log, without printing its value. Do not read any .env file. Open a pull request titled "Help desk keys" and wait for the checks.You will see recreated screen
| Key | Environments | Value |
|---|---|---|
| SVC_INTAKE_DATABASE_URL | Preview | •••••••• |
| SVC_INTAKE_DATABASE_URL | Production | •••••••• |
| SVC_CLOCK_DATABASE_URL | Preview, Production (separate) | •••••••• |
| SVC_INBOUND_SECRET | Preview, Production (separate) | •••••••• |
| SVC_EMAIL_MODE | All | off |
- Preview points at the development project, Production at the live one: never the same password in both.
- Redeploy (merge, or Redeploy on the preview) before testing.
Check it worked
Vercel lists the five variables for Preview and Production; the password manager holds the four secrets; docs/KEYS.md names them, with no values; the start-up check test is green.
Fastest path
Do the development project, Vercel Preview and the KEYS.md prompt now. Do the live project's two passwords at the end of this session, after the access migration has been deployed, in one sitting.
If it goes wrong
The build stops with "Invalid URL", or the start-up check says a key is malformed
The value was pasted with quotes, a NAME= prefix or a space, or the password has a character that needs encoding. Paste the value again, alone. A key can be present and still wrong: we once had a variable whose value was its own name.
"password authentication failed for user svc_intake"
The user name must carry the project reference when it goes through the pooler (svc_intake.tsrqponmlkjihgfedcba), and the password must be the one set in that project. Check both in the password manager; do not switch to the service key to make it work.
Claude Code asks you to paste the secret so it can test
Refuse. Say: I set secrets myself in Vercel. Test against the preview deployment, or add a fake value in the test only.
A reply joins its ticket
An email carries a Message-ID header, and a reply names the message it answers in its In-Reply-To and References headers [1]. The desk makes each outgoing message's ID before saving it, stores it in channel_message_id, and sends it in that header, so a reply can be matched exactly. The ticket number in the subject is the second try. The subject words and the sender alone are never used: one person has many tickets, and subjects are reused.
Session 4: Intake, threading and routing
35 minutesWhy
Threading is the first thing customers notice: a reply that opens a second ticket doubles the work and loses the history. Matching on message headers first is exact, and a unique message id makes the same email harmless when it arrives twice. Sending stays off until you choose otherwise, and a send that fails must say so, because a page that claims an email went when it did not is worse than no email.
Do this
Read node_modules/next/dist/docs/ for route handlers, then lib/access/routes.ts, docs/svc-tables.md and docs/svc-operations.md. On a new branch helpdesk/intake:
1. Build POST /api/svc/intake, connecting with SVC_INTAKE_DATABASE_URL (never the service key). Add it to docs/matrix.json as the one public address of this module and regenerate the routes with node scripts/gen-routes.mjs: it refuses any request without the SVC_INBOUND_SECRET header (compared in constant time), and any portal or catalogue post without a signed-in session.
2. A new email or portal request makes a svc_ticket numbered by the numbering function and a svc_ticket_message. The requester comes from the signed-in session (portal) or is matched to core_person by address (email); an unknown sender leaves requester_person_id empty and keeps the address in ext for the lead.
3. Threading: match a reply by In-Reply-To and References against channel_message_id, then by the ticket number in the subject; never by subject words or sender alone. A reply to a resolved ticket reopens it; to a closed or archived ticket, a new ticket with parent_ticket_id set. Ignore mail with an Auto-Submitted header and mail from our own addresses. Every outgoing message gets its Message-ID made before it is saved.
4. Outbound email obeys SVC_EMAIL_MODE: off sends nothing and says so on the ticket; test sends only to an allow-list of our own addresses; on sends. Count a send as done only when the provider returns a message id; otherwise log the provider's status and reason (never the key, address or body) and show that it was not sent.
5. Routing at creation: the category's default_group_id; the group member whose last assignment is oldest; priority from impact and urgency using the table in docs/svc-tables.md. One macro (reply, set pending_requester, assign) that runs as the agent who clicks it.
6. Tests with email fixtures: a new email makes one ticket; its reply joins it; the same reply sent twice adds nothing; a reply with a rewritten subject still joins by headers; an auto-reply is ignored; a request with no secret is refused; a refused send shows "not sent" and logs a line; a macro that sets is_major_incident is refused for an agent. For each test, show me it failing with the fix removed, then passing.
Push, open a pull request titled "Help desk intake", wait for every check, and report in plain words.You will see recreated screen
- Red first: a test that has never failed may be unable to fail.
- The honest message when email is off. Nothing claims a send that did not happen.
Check it worked
The pull request is green. On the preview, as requester.test, a request from /support/new appears on /desk in the right group with a priority; the ticket shows "Not sent: email is off" for the acknowledgement.
If it goes wrong
The ticket says the acknowledgement was sent, but nothing arrived
The code reads success without checking the provider's answer. Say: Count a send as delivered only when the provider returned a message id. On failure, log status and reason without the key, address or body, and show "not sent". Add a test with a fake provider that refuses. Our own operations lead was locked out of production by a page that said "sent".
Two robots answer each other all night
An auto-reply was treated as a customer reply. Say: Ignore mail with an Auto-Submitted header other than no, and mail from our own addresses, with a test for each.
The intake address answers without the secret
Stop and fix before merging. Say: /api/svc/intake must refuse with no secret and with a wrong one. Show me both requests and their responses, and add them as tests. In a prior build, 376 of 449 route handlers answered with no sign-in check.
The same email made two tickets
channel_message_id is not unique, or the route inserts before checking. Say: Make the insert rely on the unique index on channel_message_id and treat the conflict as "already stored", with a test that posts the same email twice.
The service-level clock counts business time only
A timer on wall-clock time counts nights, weekends and holidays and ignores pauses: tickets look late when nobody could work on them and fine when they have really sat. The clock starts at creation or, outside hours, at the next opening; counts only minutes inside opening periods; and stops in a pause status. Times are stored in UTC and the sums are done in the business hours' time zone with the language's own time-zone support, so a day when the clocks change still comes out right [2]. ISO/IEC 20000-1 expects service levels to be agreed and monitored [3].
Session 4: The service-level clock, with its test matrix written first
40 minutesWhy
Due times are the desk's promise to its customers, and wrong arithmetic is invisible until someone complains. Writing the test matrix first, from the tickets you worked by hand, means the code has to match your answers, not the other way round. A pure function (same inputs, same output, no database) is the easiest code there is to test, and the clock route that uses it is then only plumbing.
Do this
On a new branch helpdesk/clock:
1. Write the tests first, in tests/svc-clock.test.ts, from tests/fixtures/helpdesk-clock-cases.json: tickets A to E with every expected due time, plus a request at exactly 17:00 (starts next opening), a request on the holiday (starts next working day), a window across the day the clocks change in our time zone, and ticket A resolved at 11:30 (resolution breached by 90 minutes). Run them and show me they fail, because there is no code yet. Never change an expected value.
2. Then write lib/svc/clock.ts with two pure functions: dueAt(start, minutes, hours, holidays, pauses) and businessMinutesBetween(from, to, hours, holidays). Store UTC; do the sums in the business hours' time zone with the language's own time-zone support, never hand-made offsets. Make the tests pass.
3. Build the clock as a server function that connects with SVC_CLOCK_DATABASE_URL. On every create, priority change and status change: pick the policy by conditions and priority_order; write first_response_due_at and resolution_due_at; set first_responded_at from the first public agent message; read pause periods from the system notes; upsert the first_response and resolution rows of svc_sla_event (next_response is stored in the policy, not computed). Run it when an agent or the lead opens the queue; no scheduled job.
4. At 80 percent of a target's business minutes, insert one core_action_item for the group's manager (source_type svc_ticket, source_id the ticket, the metric in ext, with a unique index so a second run adds nothing) and show the ticket as at risk on /desk/lead. When the target passes, set breached.
5. A test as the table owner blanks the due times and events of the four fixture tickets loaded into the test database, runs the clock, and checks it writes back exactly the hand-worked values.
Push, open a pull request titled "Help desk clock", wait for every check, and report in plain words.You will see recreated screen
- Failing for the right reason: the code does not exist yet.
- Every expected value is the one you worked by hand in Session 2.
- The warning is written once, however often the queue is opened.
Check it worked
The clock test is green with the fixture values unchanged (open the pull request's Files changed tab: tests/fixtures/helpdesk-clock-cases.json must not appear). On the preview, /desk/lead lists a SYNTHETIC ticket as at risk before it breaches.
If it goes wrong
A test is "fixed" by changing the expected time
Say: Revert the change to the expected values. They are worked by hand. Find which rule differs: the clock's start, the holiday, or the pause. Changing a check to get green is the one thing the clamps from Session 10 exist to stop.
Due times are an hour out on some days
The sums use a fixed offset instead of the time zone. Say: Use the language's own time-zone support for the business hours' zone, never a hand-made offset, and add the clock-change day as a test.
The at-risk warning appears again every time the queue opens
There is no unique index on the warning. Say: Add a unique index on core_action_item (source_type, source_id, the metric in ext) in a new spine migration and insert with on conflict do nothing.
The clock's upsert is refused by row-level security
svc_clock has no read right on svc_sla_event. Add the cell in docs/matrix.json and regenerate; never widen the policy by hand.
Incident, problem and change
ITIL 4 separates restoring service now (incident), finding the cause (problem) and changing safely (change enablement) [4]. Only the lead flags a major incident; related tickets link to it with parent_ticket_id and share one update. A problem collects incidents, records the root cause and a workaround, and becomes a known error when the workaround is written. A change is standard, normal or emergency; in this build all three keep the same record and the same two gates.
Session 4: Resolve and survey, then a major incident, a problem and a PLC change
40 minutesWhy
These are the flows auditors and plant engineers will judge the desk by: a ticket cannot be closed without an answer, a satisfaction score cannot be counted twice, and a PLC cannot be changed without a back-out plan and the plant's own change control. Each rule lives in the database with a test that tries to break it, so it holds for every screen and import, and walking the flows as the demo logins proves the matrix gives each role what it needs.
Do this
On a new branch helpdesk/flows:
1. Resolve: a trigger refuses an update to resolved unless a public agent message exists after the last status change. It fires only on update, never on insert (Session 5 inserts tickets the old tool resolved; the insert-only import login never updates). The clock sets resolved_at, prepares a survey link signed with SVC_SURVEY_SIGNING_KEY and good for one answer, and sends it only as SVC_EMAIL_MODE allows (otherwise the link shows on the ticket). The intake route writes one svc_csat_response; a second answer is refused. Resolved tickets close after 5 days.
2. Saving: every update to a ticket includes its row_version in the WHERE clause, so a stale save (two agents on the same ticket) is refused with a clear message instead of overwriting.
3. Major incident, problem, knowledge: the lead sets is_major_incident; related tickets link by parent_ticket_id; one macro posts one public update to each. The lead creates a problem linking at least two incidents, records root_cause and workaround and sets known_error; the owner drafts an internal article; the lead publishes it. A published article that changes is a new row with the next version; the old one is retired.
4. Change: a recursive query lists every item affected by a configuration item (depends_on and connects_to followed backwards, hosts forwards) for the impact analysis. Refuse in the database: authorize with no back-out plan; scheduled for a plc or hmi item with no ext.moc_ref; scheduled by the person who created the change. Flag a second change on the same item in an overlapping window.
5. A catalogue item "New user account" in the Service desk group; raised from /support/new it becomes a service_request ticket.
6. Write docs/svc-events.md with the line where each of svc.ticket.created, svc.ticket.resolved, svc.sla.breached, svc.ticket.complaint and svc.change.authorized fires; svc.kb_gap.detected is written down as not built (it needs portal sessions).
7. Tests for every refusal above and for each flow as its demo login, each shown failing first.
Push, open a pull request titled "Help desk flows", wait for every check, and report in plain words.When it is merged and on the preview, walk it yourself on your phone: as agent.test, try to resolve a ticket with no reply (refused), then reply and resolve; as requester.test, answer the survey twice (second refused); as agent.test, move the seeded PLC change to authorize with no MOC reference, then as approver.test try to schedule it (refused), add the reference as agent.test, and schedule it as approver.test.
You will see recreated screen
- Each rule is a test that tries to break it.
- The impact list goes into the change's impact analysis; check it against the drawing in this chapter.
You will see recreated screen
- The impact list from the recursive query.
- The database's refusal, in words the approver understands.
Check it worked
Every refusal in the walk-through is refused on the preview, and every allowed step works as its demo login. docs/svc-events.md lists five events with their lines and one not built.
If it goes wrong
An agent's save silently overwrote another agent's change
The update does not check row_version. Say: Include row_version in every ticket update's WHERE clause and refuse a stale save with a message. Add a test that starts two saves from the same copy and expects exactly one to succeed.
The impact list misses the items the PLC hosts
The query only follows links backwards. Say: Follow hosts forwards from the item as well, and add the hosted item to the test. Also check the seed stores connects_to from the user of the link, as docs/svc-tables.md says.
The survey link works twice
The token is not single-use. Say: Mark the token used in the same transaction that writes the answer, and rely on the one-answer-per-ticket rule; test a second answer.
A step is refused as a demo login
That is a gap in the matrix, not a reason to widen a policy. Add the cell to docs/matrix.json, add the line to docs/svc-operations.md, regenerate, and rerun.
Knowledge check
With business hours 09:00–17:00 on weekdays and no holiday, a ticket arrives Saturday 11:00 with a 240-minute first-response target. When is the first response due?
Knowledge check
A normal change on a PLC has both plans but no ext.moc_ref. What happens when the approver schedules it?
References
- RFC 5322: Internet Message Format (Message-ID, In-Reply-To, References). https://www.rfc-editor.org/rfc/rfc5322
- MDN: Intl.DateTimeFormat, time zones. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
- ISO/IEC 20000-1:2018 Service management system requirements. https://www.iso.org/standard/70636.html
- Giva: IT service desk software guide (ITIL 4 practices). https://givainc.com/blog/it-service-desk-software
- ISA: ISA/IEC 62443 series of standards. https://www.isa.org/standards-and-publications/isa-standards/isa-iec-62443-series-of-standards
Chapter 4 · Sessions 5 and 6
Move the records in, prove the figures, switch the old tool off
Real tickets arrive only at the end, and only after a rehearsal. Session 5 builds an import you can run twice, rehearses it on the development project with a redacted copy IT has approved in writing, compares a week's figures with the old tool's own, and removes the copy the same day. Session 6 runs the final import into production only through the import workflow a person starts from main, with an export owner two approved, switches email over, switches the importer off, and cancels the old subscription with the saving written from invoices.
25 min4 stepsSessions 5–6ends with the module's gate
By the end of this chapter you can
- Map the old tool's statuses and fields, and build an import that changes nothing when it is run a second time.
- Rehearse on the development project with a redacted, IT-approved copy, with counts that match and every difference explained, and remove it the same day.
- Run the final import into production only through import-helpdesk.yml, cut over, set the importer to NOLOGIN, and record the saving from real invoices.
| Old record | Arrives as | Rule |
|---|---|---|
| Open ticket and its comments | Live svc_ticket and svc_ticket_message rows | Original created_at and sent_at kept; status mapped; private comments stay internal |
| Closed ticket before the history date | svc_ticket with archived_at set | Readable and searchable; any update refused |
| User | core_person (matched by address, or an external person with no sign-in) | Doubtful matches listed for a person to decide |
| Organisation | account_ref, by exact name, when the CRM module exists | Otherwise empty and kept in ext |
| Article | svc_kb_article, status draft, version 1 | The lead reviews and publishes; customer details removed first |
| Old ticket number | A legacy key in ext (for example freshdesk:1042), unique | Running the import twice adds nothing; replies quoting the old number thread |
Session 5: Map the old tool, and build an import you can run twice
40 minutesWhy
An import that cannot be repeated safely forces you to get it right in one go on the day you switch, which is the worst day to find a mistake. A unique legacy key on every imported row makes a second run add nothing, so you can rehearse, fix and rerun as often as you need. A mapping file with an "unmapped" report, instead of guesses, means every old status and group lands where someone decided it should.
Do this
Read ten tickets in your private ten-ticket export beside the old tool and write the old tool's names for status, priority, channel, type, group and tag. Real exports are taken by you from the old tool's own export page and never go into the repository or a chat. Then:
On a new branch helpdesk/import:
1. Write scripts/import/map.json from the old names I list below onto our seven statuses, p1–p4, eight channels, seven ticket types, groups and categories. Anything I have not mapped goes to an "unmapped" report and is never guessed.
2. Write a new migration (never edit an applied one) adding a unique index on the legacy key in ext (the old tool's name and id) on svc_ticket, svc_ticket_message and svc_kb_article.
3. Write scripts/import/run.mjs. It reads an export file (the old tool's own export format) and writes with the insert-only svc_import login in IMPORT_DATABASE_URL, from the environment; it never prints it. Open tickets become live rows with original times; closed tickets before HISTORY_BEFORE get archived_at; comments become messages in order, private ones internal; users match core_person by address or become external people; articles become drafts at version 1. It only inserts, with on conflict do nothing on the legacy key, and lists tickets the old tool resolved with no public agent reply for the lead. --dry-run writes nothing and prints counts.
Also scripts/import/count.mjs <file>, which I run on my own computer: prints the file's sha256 and the counts per record type, never any content; and scripts/import/redact.mjs <file> <out>, which I run for the rehearsal copy: replaces every person's name, email address and phone number with a consistent placeholder (the same person always gets the same one).
4. Extend the intake route: a reply quoting an old ticket number joins that ticket by its legacy key; a reply to an archived ticket opens a new ticket with parent_ticket_id set.
5. Write .github/workflows/import-helpdesk.yml, started only by hand (workflow_dispatch) by a person, refusing any branch but main, with inputs target (development or production), file and mode (dry-run or write). It downloads the file from the private Storage bucket imports of the target project; computes its sha256; refuses the run unless that sha256, the target and the expected counts per record type are listed in docs/imports/helpdesk-approved.md on main; runs the import; and fails if any count (written plus skipped) differs from the listed one. Secrets are repository secrets SVC_IMPORT_DATABASE_URL_DEV and SVC_IMPORT_DATABASE_URL_PROD, typed by me. No GitHub environments and no "required reviewers" (not available for private repositories on our plan): the reviewed pull request that adds the approved line is the approval. It prints a count table: rows expected, rows written, rows skipped with a reason.
6. docs/imports/helpdesk-approved.md: one heading per approved export with target, file name, sha256, expected counts, IT's approval reference and, for the rehearsal, the date it was removed. supabase/snippets/remove-helpdesk-rehearsal.sql, for me to run in the development SQL editor: deletes only rows whose ext holds a legacy key (tickets, messages, external people the import created, articles), prints the counts, and refuses unless the database is acme-platform-dev. Add the new secrets' names to docs/KEYS.md.
7. Tests with a fixture export: running twice changes nothing; the import login's update is refused; a ticket resolved with no reply is listed; an archived ticket refuses updates; a reply quoting an old number joins it; the import login cannot insert svc_sla_event or svc_change_request; the workflow refuses a file not listed and fails on a count mismatch.
Push, open a pull request titled "Help desk import", wait for every check, and report in plain words.
The old tool's names:
<paste your list of old statuses, priorities, channels, types, groups and tags>You will see recreated screen
- The mapping is a file you can read and correct, not code.
- Run twice equals run once: the property the whole rehearsal depends on.
- Unmapped values wait for a person, never a guess.
Check it worked
The pull request is green; the second-run test reports nothing inserted or updated; the unmapped report lists anything you still need to decide, and you have decided each.
If it goes wrong
Claude Code asks for the real export, or an API token, to try it
Refuse. Say: Test only against the fixture export. I take the real export myself, and the workflow reads it from the private imports bucket.
Claude Code adds a GitHub environment with required reviewers, or runs the import on merge
Say: No environments and no import on merge: a person starts import-helpdesk.yml from main, and the merged line in docs/imports/helpdesk-approved.md is the approval. Required reviewers are not available for private repositories on the Team plan.
The second run creates duplicates
The legacy key is not unique, or the script inserts before looking. Say: Rely on the unique index on the legacy key with on conflict do nothing, never an update, then run the fixture import twice and show 0 inserted.
Old tickets arrive with today's date
The script let the database default created_at. Say: Keep the original created_at and sent_at from the export, and add a test that an imported ticket keeps its old date.
Session 5: Rehearse on the development project with an IT-approved copy, and compare a week
45 minutesWhy
The rehearsal is where mistakes are cheap. Running the real import against the development project shows you real volumes, real oddities and real figures without touching production, and comparing one full week with the old tool's own reports is the evidence the owners need before they agree to switch. Real records are personal data, so the copy goes into the development project only redacted and with IT's written approval, and comes out again the same day, with the date recorded.
Do this
Ask IT, in writing, before any real record leaves the old tool:
Subject: Approval to rehearse the help desk import on our development database
We plan to copy the help desk's tickets, comments, users and articles from <old tool> into our
development database (acme-platform-dev, Supabase, region us-east-2) for one rehearsal on <date>,
and delete them the same day. Names, email addresses and phone numbers are replaced with placeholders
before the copy is loaded. Access: the two platform owners and the support lead. Nothing is shared
outside the company. Please confirm in writing.When IT approves, on the rehearsal day: take the export from the old tool's own export page into your private folder, run node scripts/import/redact.mjs on it, then node scripts/import/count.mjs on the redacted copy for its sha256 and counts. Record them, with IT's approval reference, in docs/imports/helpdesk-approved.md through a pull request owner two approves and merges. Set the development project's import login password in its SQL editor (alter role svc_import with login password '…';, from the password manager), and type the repository secret SVC_IMPORT_DATABASE_URL_DEV (the development connection string with user svc_import.tsrqponmlkjihgfedcba). Upload the redacted copy to the private bucket imports on the development project.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets
Development Storage: a private bucket named imports; upload the redacted copy.
https://github.com/acme-ops/acme-platform/settings/secrets/actions
GitHub: Settings, Secrets and variables, Actions: New repository secret.
https://github.com/acme-ops/acme-platform/actions/workflows/import-helpdesk.yml
Run workflow from main: target development, mode dry-run first; then mode write; then write again (it must change nothing).
The rehearsal import has run on the development project. On a new branch helpdesk/rehearsal:
1. Add a read-only report panel to /desk/lead for a date range: first response (median, in business minutes to match the old tool, which counts business time), time to resolution (median business hours minus paused time), SLA attainment (tickets meeting all targets / tickets under an SLA), CSAT (4 and 5 positive) and backlog. Show "No data" where nothing is measured. Test it on the fixture: median first response 120 business minutes, median time to resolution 15.25 hours, SLA attainment 3 of 4 (75%).
2. Write docs/cutover.md with: the workflow run links and their count tables, every skipped row and why, the unmapped values and what we decided, and an empty two-column table for the old tool's figures beside the platform's for the last full week.
Push, open a pull request titled "Help desk rehearsal", wait for the checks, and report.Fill in the old tool's column from its own report for the same week, and the platform's from the panel on the development preview. Explain every difference in the file. Then, the same day: run supabase/snippets/remove-helpdesk-rehearsal.sql in the development SQL editor, delete the file from the bucket and your local copies, write the removal date in docs/imports/helpdesk-approved.md, reload the made-up data with npm run seed:dev, and tell IT in writing.
You will see recreated screen
| Record | Expected (approved) | Written | Skipped (reason) |
|---|---|---|---|
| Tickets open | 63 | 63 | 0 |
| Tickets closed (history) | 2,140 | 2,138 | 2 (spam, listed) |
| Comments | 11,802 | 11,790 | 12 (on the 2 spam tickets) |
| Users | 418 | 418 | 0 |
| Articles | 57 | 57 | 0 |
- A green run means the file was the approved one and every count matched. Read the table anyway.
- Every skipped row has a reason, and the reasons add up.
You will see recreated screen
| Measure | Old tool (report) | Platform | Difference explained |
|---|---|---|---|
| First response, median | 1 h 52 m (SLA report) | 1 h 52 m | none |
| Time to resolution, median | 14.0 h | 13.1 h | old tool counts the pending status; ours pauses it |
| SLA attainment | 88% | 88% | none |
- A difference is fine when it is explained. A difference nobody can explain means you are not ready.
Check it worked
IT's written approval is filed; the copy was redacted; the second write run reported nothing inserted; expected, written and skipped counts add up for every record type; docs/cutover.md explains every difference in the week's figures; the report panel's fixture test is green; and the same day the development project holds no row with a legacy key, with the removal date in docs/imports/helpdesk-approved.md.
Fastest path
Run dry-run, write and write-again back to back from the Actions page: three runs, one sitting, and the third proves the import can be rerun on cutover day.
If it goes wrong
The figures differ and you cannot say why
Do not tune the clock to match. The usual causes: calendar against business time, another holiday list, another pause rule, another time zone, merged or spam tickets, solved against closed. Ask Claude Code: For these three tickets, show the old tool's dates and ours side by side and say which rule gives the difference.
The run fails with "password authentication failed"
Check the user name carries the project reference (svc_import.tsrqponmlkjihgfedcba) and the password is the development one. Paste the secret value alone, with no NAME= or quotes.
The run refuses the file, or fails on a count
It is doing its job: the file is not the one owner two approved, or it changed. Run count.mjs on the file you uploaded, record its sha256 and counts through a pull request, and run again. Never loosen the check.
A screen shows a number nobody measured (CSAT 0%, deflection 100%)
Say: Show "No data" for any measure with no data behind it, never 0, and add a test per panel with an empty range. The deflection rate needs portal sessions, which this build does not record.
Session 6: The final import into production, through the pipeline
45 minutesWhy
Production holds the plant's real records, so the final import runs only through the same tested workflow as the rehearsal, started by you from main, with production's secret typed by you and an export whose fingerprint and counts owner two approved in a merged pull request, instead of from anyone's laptop. The old tool goes read-only first, so nothing changes in it while the copy runs, and the counts are checked against the rehearsal's before anyone is told the desk has moved.
Do this
Write the cutover plan in docs/cutover.md with the support lead: the date, who tells staff and customers, how to switch back, and the date after which switching back is no longer possible. Then, on the day:
https://github.com/acme-ops/acme-platform/settings/secrets/actions
Repository secrets: add SVC_IMPORT_DATABASE_URL_PROD (live project, user svc_import.abcdefghijklmnopqrst, password set by you in the live SQL editor).
- Turn off the old tool's email intake (do not delete anything), so no new ticket lands there.
- Take the final export from the old tool's export page, run
node scripts/import/count.mjson it, and record its sha256 and counts in docs/imports/helpdesk-approved.md through a pull request owner two approves and merges. - Upload it to the private bucket imports on the live project.
- Start the workflow from main: target production, mode dry-run, then write. It refuses an export not listed and fails on any count mismatch.
- Compare the count table with the rehearsal's: the same record types, every skip explained.
- At your mail host, forward the support address to the intake address with SVC_INBOUND_SECRET, and set svc_support_group.email_alias. Put the portal link where the old one was.
- In Vercel, set SVC_EMAIL_MODE for Production to test; send a request and reply from your own address and check it threads; then set it to on.
https://vercel.com/acme-ops/acme-platform/settings/environment-variables
Vercel: set SVC_EMAIL_MODE, then redeploy production from the Deployments page.
Production import is done. Run the production checks read-only and report, changing nothing: count svc_ticket, svc_ticket_message, core_person (external), svc_kb_article rows carrying a legacy key and compare them with the counts table I paste below; confirm an archived ticket refuses an update (in a transaction you roll back); confirm three imported tickets' message order and dates. Add the results to docs/cutover.md on a new branch helpdesk/cutover, open a pull request titled "Help desk cutover record" and wait for the checks.
Counts from the production run:
<paste the workflow run's count table>You will see recreated screen
- No one person can write real records into production: the file must be the one owner two approved in a merged pull request.
- Any count that differs from the approved line fails the run.
Check it worked
The production run started from main with an approved export, and its counts match the approved line with every skip explained; a test email from your own address threads into one ticket; SVC_EMAIL_MODE is on; the first real tickets arrive on /desk; the cutover record pull request is merged.
If it goes wrong
Production pages fail with "column does not exist" after the switch
A migration was merged but is not in production. Check the deploy workflow's last run and the daily freshness check from Session 11; do not run db push by hand. Our live database once fell nine migrations behind main.
Customers reply to old notification emails and get a new ticket
Their replies quote the old number. Check the reply quotes it as the old tool did; if the export had no message ids, the legacy-key match from Step 11 is what threads them. Add the failing email as a fixture test.
The page says the reply was sent and the customer got nothing
Check the provider's dashboard for the send and the app's log line. A send counts only with a provider message id; if the log says refused, the sending domain is usually not verified yet. Set SVC_EMAIL_MODE back to test until it is.
Session 6: Retire the old tool, switch the importer off, and record the saving
30 minutesWhy
The module is finished when the old bill stops, and the saving is a fact only when it comes from invoices. A login that can write imported rows has no business existing once the move is done, so the importer is set to NOLOGIN at cut-over, and deleting the export from the bucket and your computer closes the last place real records sit outside production's tables.
Do this
Store the old tool's final full export in the company's records store (not the repository), delete it from the imports bucket and your computer, read the old tool's cancellation terms on your own account page (notice, renewal date, export window), and cancel or write the date the plan ends. Then:
The final import is done. On a new branch helpdesk/retired: a migration (npx supabase migration new helpdesk_importer_off) that sets svc_import to NOLOGIN, with a test that it cannot log in; in docs/KEYS.md mark SVC_IMPORT_DATABASE_URL_DEV and _PROD removed with today's date. Then update docs/helpdesk-inventory.md: mark each channel and queue replaced, retired or still on the old way, with today's date; and add to docs/cutover.md the saving: the old bill from the invoices (I will paste the figures), minus what the module adds to services we already pay for, plus any email-sending charge. Open a pull request titled "Help desk retired" and wait for the checks.https://github.com/acme-ops/acme-platform/settings/secrets/actions
After it merges and the deploy workflow has applied the NOLOGIN migration: delete both SVC_IMPORT_DATABASE_URL secrets.
Delete the ten-ticket export and any other local copy.
You will see recreated screen
- Every figure carries the invoice it came from; no estimate.
- Anything not replaced is written down, not hidden.
Check it worked
The old tool is cancelled (or its end date is written), the final export is stored outside the repository and gone from the bucket, svc_import is NOLOGIN and its secrets are deleted, and docs/cutover.md records the saving from invoices.
If it goes wrong
Someone wants to keep the importer for a late batch
Set it to NOLOGIN anyway. A late batch is a new export: it is approved through docs/imports/helpdesk-approved.md and the login is switched on by a person for that one run, then off again.
The vendor's notice period means another renewal
Write the end date and the renewal amount in docs/cutover.md. The saving starts then; do not count it earlier.
Knowledge check
Why can the import be rehearsed, fixed and run again as often as needed?
Knowledge check
The platform's median time to resolution is lower than the old tool's for the same week. What do you do?
References
- Freshdesk API documentation. https://developers.freshdesk.com/api/
- Zendesk Developer Docs: Ticketing API. https://developer.zendesk.com/api-reference/ticketing/introduction/
- GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
- ISO 10002:2018 Customer satisfaction: guidelines for complaints handling. https://www.iso.org/standard/71580.html
Chapter 5 · 12 questions · 80% passes
Final assessment
Twelve questions across the module. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.
15 min12 questions≈ 15 minutesRetake allowed
Your result
CivOps AI Academy
Help Desk and Service Management: Tickets, SLAs, Incidents, Changes and the CMDB
Element M19 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.