Skip to the lesson
CivOps AI Academy · M19Help Desk and Service Management: Tickets, SLAs, Incidents, Changes and the CMDB
0%

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

From a request to a surveySix channels (email, portal, chat, phone, Slack or Teams, API) feed one intake route, which makes a ticket. The ticket is routed to a group, worked by an agent, resolved and followed by a survey. EmailPortalChatPhoneSlack or TeamsAPIIntake routematches the person,numbers the ticketTicketsvc_ticket, status newRoutingcategory, group, priorityAgentreplies, notes, macrosResolvedlast public replySurveyone answer per ticketThe service clock runs from the ticket to resolution; every step leaves a message or a status change.
From a request to a survey. Every channel ends at one intake route. It matches the person, numbers the ticket and stores the first message; routing picks the group, priority and agent; the last public reply is the recorded resolution, and a survey follows.
CapabilityWhat it doesTierBuilt in these six sessions
Omnichannel intakeEmail with threading, portal, phone logging, API; the requester matched to a personMVPEmail, portal, phone and catalogue. Chat widget and Slack or Teams: written down, not built
Ticket workflowTypes, statuses, priority from impact and urgency, groups, assignment, internal notes, parent and childMVPYes; merging tickets and assignment by skills are not built
SLA managementFirst response and resolution targets on business hours, holidays and pauses; breach warningsMVPYes; next response is stored, not computed
Knowledge baseInternal and public articles with versions; suggestions while typingMVPYes; the deflection rate needs portal sessions and is written down only
Service catalogueRequestable items with forms (reusing the M01 form engine)STDOne item, as an ordinary service request
Incident, problem, changeMajor incident flag, problems with root cause, changes with plans and approvalSTDYes
CMDB (IT and OT)Configuration items including PLCs, HMIs and SCADA servers, with relationshipsSTDYes
CSAT and reportingSurveys on resolve; first response, time to resolution, SLA attainmentSTDYes
AI assistSuggested category, summaries, replies, always approved by the agentBICNot built
Step 1

Session 1: Inventory the old desk from its own reports and bills

60 minutes

Why

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:

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On 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

claude — acme-platform
⏺ Bash(git switch -c helpdesk/inventory)
⎿ Switched to a new branch 'helpdesk/inventory'
⏺ Write(docs/helpdesk-inventory.md)
+Every number here comes from the tool's own pages or our invoices. Never estimate.
+## 4. The last four full weeks (from the tool's own reports)
+| Measure | Value | Report name | Date range | Business or calendar time |
+| First reply time | not yet read | not yet read | not yet read | not yet read |
1
⏺ Bash(gh pr create --title "Help desk inventory")
⎿ https://github.com/acme-ops/acme-platform/pull/61
⏺ Pull request #61 adds the empty inventory form: nine sections, every cell "not yet read". I have not filled in any figure. Fill it in from the tool's reports and your invoices.2
Claude Code writes an empty form and stops. It does not fill in figures: those come from you.
  1. Every figure has a column for where it came from. That column is what makes Session 6's comparison honest.
  2. The form is empty on purpose. If Claude Code offers "typical" figures, refuse them.

You will see recreated screen

your help desk tool · Reports
OverviewTicketsSLASatisfactionExport
SLA achievement · Plant IT and OT queue
Date range4 weeks to Sunday1
HoursBusiness hours (Mon–Fri 07:00–16:00)2
WeekTickets solvedFirst reply (median)SLA met
1411 h 52 m88%
2382 h 10 m84%
3441 h 41 m91%
4402 h 03 m85%
The old tool's report page, as you copy from it (the stamping plant's desk). Copy the report name and the date range as well as the number.
  1. The date range: Session 6 compares the same days.
  2. 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.

The fifteen tablesFive groups of svc_ tables beside the spine: desk setup, the ticket, requests and knowledge, problem and change, and configuration. Setup and the spine feed the ticket; the ticket links to problems and changes, which point at configuration items; configuration items point at the spine's equipment and sites. Desk setupsvc_support_groupsvc_business_hourssvc_sla_policysvc_categorysvc_macroThe ticketsvc_ticketsvc_ticket_messagesvc_sla_eventsvc_csat_responseThe spine (core_)core_personcore_sitecore_equipmentcore_attachmentcore_approvalcore_commentcore_action_itemRequests and knowledgesvc_catalog_itemsvc_kb_articleProblem and changesvc_problemsvc_change_requestConfigurationsvc_configuration_itemsvc_ci_relationshipEvery table also carries the standard columns: id, site_id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext.
Fifteen tables in five groups beside the spine. The desk's own tables point at each other and at the spine; links to other modules are soft.
TableHoldsColumns (type; req = required)
svc_support_groupA team or queuename 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_hoursWorking hours and holidaysname text req; timezone text req; schedule json req; holidays json
svc_sla_policySLA targets and conditionsname 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_categoryThe category treename text req; parent_id → svc_category; default_group_id → svc_support_group
svc_ticketA ticketticket_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_messageA public reply or internal noteticket_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_eventOne metric on one ticketticket_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_itemA requestable servicename 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_problemA problem or known errorproblem_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_requestAn IT or OT changecr_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_itemAn IT or OT itemci_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_relationshipA dependency between itemsfrom_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_articleA knowledge articletitle 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_macroA saved reply and set of actionsname text req; actions json req; group_id; active bool req
svc_csat_responseA satisfaction answerticket_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].

Step 2

Session 2: Check the spine, then write the fifteen tables and their tests

40 minutes

Why

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

Paste into Claude Code
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.

Paste into Claude Code, then paste the table from this page where it says
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

claude — acme-platform
⏺ Read(docs/svc-tables.md)
⎿ Read 64 lines
⏺ Bash(npx supabase migration new helpdesk_tables)
⎿ Created new migration at supabase/migrations/20261102091500_helpdesk_tables.sql
1
⏺ Write(supabase/migrations/20261102091500_helpdesk_tables.sql)
+create table public.svc_change_request (
+ ...,
+ status text not null check (status in ('draft','assess','authorize','scheduled',
+ 'implementing','review','closed','failed','rejected')),
+ constraint plans_before_authorize check (status not in ('authorize','scheduled',
+ 'implementing','review','closed') or (implementation_plan is not null and backout_plan is not null))
+);
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m04s ci / build pass 3m12s clamps pass 1m40s
⏺ Pull request #63 is green. It adds 15 tables with row-level security on and forced, and no access rules yet. 48 tests passed, including 11 that try to store bad data and are refused. docs/matrix.json has 15 new rows with empty cells.3
Claude Code writes the migration, the tests and the matrix rows, then waits for GitHub's checks before reporting.
  1. The migration's name starts with the date and time, so it always runs after the spine migration.
  2. A rule in the table itself: no plan, no authorisation, whoever writes the row.
  3. 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.

SettingLab value
Business hoursMonday to Friday, 09:00 to 17:00, in your plant's time zone
HolidayMonday 2026-05-25
Policy for priority p3first response 240 minutes, next response 240, resolution 960 (16 business hours)
Pause statusespending_requester, pending_third_party, on_hold
TicketCreatedFirst replyFirst reply dueResolution dueResolvedResult
ATue 05-19 10:0011:00Tue 14:00Thu 05-21 10:00Thu 11:30Resolution breached by 90 minutes
BFri 05-22 15:00Tue 05-26 10:00Tue 05-26 11:00Wed 05-27 15:00Wed 14:00Met
CSat 05-23 11:00 (starts Tue 09:00)Tue 12:00Tue 05-26 13:00Wed 05-27 17:00Wed 16:00Met
DTue 05-19 10:0011:00Tue 14:00Thu 05-21 14:00 (240 minutes paused)Thu 13:30Met
E (extra case)Wed 05-20 16:3016:45Thu 05-21 12:30Fri 05-22 16:30; with a pause Thu 10:00–12:00, Tue 05-26 10:30Kept out of the four-ticket figures
One ticket on business timeA timeline drawn to scale from Friday 15:00 to Wednesday 17:00. Only Friday 15:00 to 17:00, Tuesday 09:00 to 17:00 and Wednesday 09:00 to 17:00 count; the weekend and the Monday holiday do not. The first reply is due Tuesday 11:00 and the resolution Wednesday 15:00. FriSat · closedSun · closedMon · holidayTueWedCreated Fri 15:00First reply due Tue 11:00Resolution due Wed 15:0009:00–17:0009:00–17:00Business minutes counted: Fri 120 + Tue 480 + Wed 360 = 960, the resolution target.First reply: Fri 120 + Tue 120 = 240, the first response target.countednot counted (outside hours)holiday
Ticket B on the business clock. Two business hours on Friday; the weekend and Monday's holiday count nothing; Tuesday and Wednesday supply the rest. Drawn to scale.
Step 3

Session 2: The worked tickets as a fixture, made-up data as the seed, and a look on the development project

35 minutes

Why

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

Paste into Claude Code, then paste the table from this page where it says
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.

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull
Terminal or PowerShell
npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal or PowerShell
npx supabase db push --include-seed
Open

https://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

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.1
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261102091500_helpdesk_tables.sql [Y/n] y2
Applying migration 20261102091500_helpdesk_tables.sql...
Seeding data from supabase/seeds/helpdesk.sql...
Finished supabase db push.
db push on the development project lists exactly the migrations main has and the development project does not.
  1. The reference is the development project's (tsrqponmlkjihgfedcba). If it shows abcdefghijklmnopqrst, stop: that is production.
  2. 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

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
svc_business_hourssvc_categorysvc_ci_relationshipsvc_configuration_itemsvc_ticketsvc_ticket_message
svc_ticket
2
ticket_nosubjectstatusprioritycreated_at
T-000012SYNTHETIC · HMI on press 3 frozenopenp2today 08:14
T-000011SYNTHETIC · New starter laptoppending_requesterp3yesterday 14:02
T-000010SYNTHETIC · Label printer offlineresolvedp32 days ago
The development project's Table Editor after the seed: made-up tickets, marked as made up, dated this week.
  1. Expected until Session 3 generates the access rules.
  2. 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

  1. Atlassian: Jira Service Management ITSM features. https://www.atlassian.com/software/jira/service-management/features/itsm
  2. Freshworks: Freshservice IT service desk. https://www.freshworks.com/freshservice/it-service-desk/
  3. PostgreSQL Documentation: Constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
  4. 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 loginReadsWritesNever
RequesterOwn tickets; public messages on them; published public articles; active catalogue items; categoriesNothing directly: every request goes through the intake routeInternal notes; anyone else's ticket
AgentEvery ticket, message (internal too), SLA event, group, category, macro, policy, problem, change, item, articleTickets in own groups (status, priority, impact, urgency, category, group, assignee, parent, problem, item); replies and notes; problems; changes they created; draft articlesis_major_incident, the due times, first_responded_at, resolved_at, closed_at; another group's tickets
Support leadEverything, including every draft article and the whole desk's figuresEverything an agent can, in every group; groups, hours, policies, categories, catalogue, macros; the major incident flag; publishing articles; items and relationshipsDelete anything
Change approverChanges, items, relationships, problems; tickets that point at an itemA change from authorize to scheduled or rejected, with cab_decision_at and a core_approval rowApprove a change they created
CI ownerOwn items and their relationships; changes and tickets on themOwn items (status, firmware_version, ip_address, attributes, equipment_id); relationships from them; commentsAnother owner's item
Intake route (login)People, groups, categories, catalogue, tickets, messages, published public articlesNew tickets and requester or system messages; routing at creation; reopening on a reply; one survey answerInternal notes; the clock's columns
Service clock (login)Tickets, messages, policies, hours, groups, SLA events, the requester's addressSLA events (insert and update: an upsert needs the read right too); the due and done times; resolved to closed; breach warnings in core_action_itemReply to anyone
Import login (insert-only)People, groups, categories, policies, tickets, messages, articlesInserts only: external people, tickets, messages, draft articles, each with a legacy key; set to NOLOGIN at cut-overUpdate or delete anything; SLA events, change requests
Step 4

Session 3: Put the roles in the matrix, walk every later step, and generate the rules

35 minutes

Why

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

Paste into Claude Code, then paste the cells (the table above) after it
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:

Paste into Claude Code
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

claude — acme-platform
⏺ Write(docs/svc-operations.md)
+## Gaps (no cell yet)
+- svc_clock · update · svc_sla_event: an upsert needs read on svc_sla_event
+- svc_clock · insert · core_action_item: breach warnings
+- change_approver · insert · core_approval: the board's decision
+- svc_import · insert · core_person: requesters with no account
1
⏺ 4 gaps found. I have stopped before generating anything. Tell me which to add.
> Add the cells for the gaps we agreed. Then: ...
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261104101200_policies.sql (47 policies, 8 roles)
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m31s
⏺ Pull request #66 is green. 94 access tests: 47 allowed, 47 refused, plus the cross-site test and 63 operation lines from docs/svc-operations.md, each checked to really change the row. No role has delete.3
First the walk, which stops at the gaps; then the generated rules and their tests.
  1. The walk finds the missing rights before any step needs them.
  2. The rules are generated from the matrix, never written by hand.
  3. "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

ScreenForShows
/support, /support/new, /support/t/[ticket_no]RequesterMy 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]AgentOpen 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/cisAgent, approver, CI ownerChanges with their gates; configuration items and their relationships
/desk/leadSupport leadTickets at risk, breached and unassigned; each group's load; the report panel (Session 6)
Step 5

Session 3: Build the portal, the agent queue and the lead view

30 minutes

Why

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

Paste into Claude Code
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

claude — acme-platform
⏺ Bash(ls node_modules/next/dist/docs)
⎿ 01-app 02-pages 03-architecture ...
1
⏺ I read the routing and proxy guides. Requests are checked in proxy.ts, which reads lib/access/routes.ts. I ran scripts/gen-routes.mjs to regenerate routes.ts from docs/matrix.json: 8 new screens, none public.
⏺ Bash(gh pr checks --watch)
⎿ ci / build pass screens pass (34 tests at 390 px) Vercel Preview ready
⏺ Pull request #68 is green. Preview: https://acme-platform-git-helpdesk-screens-acme-ops.vercel.app. Signed out, all 8 pages go to sign-in; each role opens only its own pages.2
Claude Code reads the Next.js guides first, generates the routes from the matrix, builds the pages and waits for the preview.
  1. If it does not read the guides, stop it and say: read node_modules/next/dist/docs/ first.
  2. Open the preview yourself: the check is what you see on a phone, not the summary.

You will see recreated screen

acme-platform-git-helpdesk-screens-acme-ops.vercel.app/desk
Open tickets · Plant IT and OT
T-000012 · SYNTHETIC · HMI on press 3 frozenp2 · due in 40 minutes · unassigned1
T-000009 · SYNTHETIC · Historian gap overnightp3 · breached 1 h 10 m ago · agent.test2
T-000011 · SYNTHETIC · New starter laptopp3 · paused: waiting for requester
Open
The agent queue on the preview at phone width: due states in words, sorted by due time.
  1. The due state is a sentence, so it reads without colour and on a sunlit phone.
  2. 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.

Step 6

Session 3: Demo logins on the development project, and a trial with the lead

25 minutes

Why

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.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/auth/users

Authentication, Users, on the development project. Check the name at the top says acme-platform-dev.

Paste into Claude Code
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

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/auth/users
Create new user
Email addressagent.test@example.com
User password••••••••••••••••1
Auto confirm user?2
Create user
Creating a demo login on the development project: create, not invite, so no email is needed.
  1. Generated and saved in the password manager first; never in a file or a chat.
  2. 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

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. PostgreSQL Documentation: Row Security Policies. https://www.postgresql.org/docs/current/ddl-rowsecurity.html
  3. 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 secretWhat it unlocksWhere it livesWho holds itNever
svc_intake and svc_clock passwordsThe database logins the intake route and the clock usePassword manager; set in each project's SQL editor; inside the connection string in VercelOwner one and owner twoPasted into Claude Code, a chat or a file
SVC_INTAKE_DATABASE_URL, SVC_CLOCK_DATABASE_URLConnections for those logins (Preview: the development project; Production: the live one)Vercel environment variablesOwnersCommitted, or used in the browser
SVC_INBOUND_SECRETProves a forwarded email came from your mail hostVercel environment variable and the mail host's forwarding settingOwnersSent in a URL, logged, or shown on a page
SVC_SURVEY_SIGNING_KEYSigns single-use survey linksVercel environment variableOwnersShared between environments
SVC_EMAIL_MODE (not secret)off, test (your own addresses only) or onVercel environment variableOwnersSet to on before Session 6's cutover
Step 7

Session 4: Set the logins' passwords and the route secrets yourself

20 minutes

Why

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):

Terminal or PowerShell
openssl rand -hex 32

Generate 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:

Supabase SQL editor, development project, typed by you
alter role svc_intake with login password '<from the password manager>';
alter role svc_clock  with login password '<from the password manager>';
Open

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.

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Vercel: Settings, Environment Variables.

Paste into Claude Code
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

vercel.com/acme-ops/acme-platform/settings/environment-variables
Environment Variables
1
KeyEnvironmentsValue
SVC_INTAKE_DATABASE_URLPreview••••••••
SVC_INTAKE_DATABASE_URLProduction••••••••
SVC_CLOCK_DATABASE_URLPreview, Production (separate)••••••••
SVC_INBOUND_SECRETPreview, Production (separate)••••••••
SVC_EMAIL_MODEAlloff
Vercel's environment variables after this step: names visible, values hidden, Preview and Production kept apart.
  1. Preview points at the development project, Production at the live one: never the same password in both.
  2. 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.

How a reply finds its ticketA sent message stores its Message-ID. A customer's reply carries In-Reply-To and References headers. The intake route matches the headers first, then the ticket number in the subject; either joins the ticket (a resolved ticket reopens; a closed one gets a new child ticket with it as parent), and with no match a new, unlinked ticket is made. Message sentMessage-ID made first,saved in channel_message_idCustomer repliesIn-Reply-To and Referencesname the message answered1 · Message headersmatch channel_message_id2 · Ticket numberfound in the subject3 · No matchnothing to joinJoins the ticketa resolved one reopens; a closedone gets a new child ticketJoins the ticketsame rules, found by numberNew ticketnot linked to any otherNever match on the subject words or the sender alone. Skip automatic replies and your own addresses.The same reply sent twice adds nothing, because channel_message_id is unique.
How a reply finds its ticket. Headers first, then the ticket number, otherwise a new ticket. A reply to a resolved ticket reopens it; a reply to a closed one starts a new ticket whose parent is the old one.
Priority from impact and urgencyA three by three grid of impact against urgency. High impact and high urgency is p1; high and medium or medium and high is p2; medium and medium, high and low, or low and high is p3; the remaining three cells are p4. UrgencyImpactLowMediumHighHighp3p2p1 · firstMediump4 · lastp3p2Lowp4 · lastp4 · lastp3An example table:high and high is p1;high and medium, or mediumand high, is p2; the reststep down to p3 and p4.Write your own and keep it.
An example impact and urgency table. The cell decides the priority, and the priority picks the policy. Write your own and keep it in docs/svc-tables.md.
Step 8

Session 4: Intake, threading and routing

35 minutes

Why

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

Paste into Claude Code
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

claude — acme-platform
⏺ Bash(npm test -- intake)
⎿ ✗ reply with rewritten subject joins by headers (fix removed) ✓ 11 passed, 1 failed
1
⏺ Bash(npm test -- intake)
⎿ ✓ 12 passed (fix restored)
⏺ Bash(gh pr checks --watch)
⎿ ci / build pass · schema / test pass · screens pass · clamps pass
⏺ Pull request #71 is green. A reply threads by its headers even with a new subject; sending it twice adds nothing; with SVC_EMAIL_MODE off the ticket says "Not sent: email is off". 12 tests, each shown failing first.2
Each new test is shown red with the fix removed, then green: proof that it can fail.
  1. Red first: a test that has never failed may be unable to fail.
  2. 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].

A paused clockThree working days drawn to scale. A ticket created Tuesday 10:00 has 960 business minutes to resolve. Tuesday 15:00 to 17:00 and Wednesday 09:00 to 11:00 are paused, so the due time moves from Wednesday to Thursday 14:00. Tue 2026-05-19091317Wed 2026-05-20091317Thu 2026-05-21091317Created 10:00Resolution due Thu 14:00counted: 5 h + 6 h + 5 h = 16 h = 960 minutespaused in pending_requester: 2 h + 2 h = 240 minutes, not countedHours of the working day (24-hour clock); nights and weekends are left out.Resolved Thursday 13:30, before the due time, so the target is met.
Ticket D with a pause. Four business hours waiting for the requester are not counted, so the 960 minutes end on Thursday 14:00.
Step 9

Session 4: The service-level clock, with its test matrix written first

40 minutes

Why

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

Paste into Claude Code
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

claude — acme-platform
⏺ Bash(npx vitest run tests/svc-clock.test.ts)
⎿ ✗ 14 failed: Cannot find module 'lib/svc/clock'
1
⏺ Write(lib/svc/clock.ts)
+export function dueAt(start: Date, minutes: number, hours: Hours, holidays: string[], pauses: Pause[]): Date {
+ // walk opening periods in hours.timezone, skipping holidays and pauses
⏺ Bash(npx vitest run tests/svc-clock.test.ts)
⎿ ✓ 14 passed A first response Tue 2026-05-19 14:00 ✓ resolution Thu 2026-05-21 10:00 ✓ breached 90 min ✓ B first response Tue 2026-05-26 11:00 ✓ resolution Wed 2026-05-27 15:00 ✓
2
⏺ Pull request #73 is green. The clock reproduces all five hand-worked tickets and the four edge cases, including the clock change. Opening the queue twice adds no second warning.3
Tests first, failing; then the code; then the same tests passing. The expected values never move.
  1. Failing for the right reason: the code does not exist yet.
  2. Every expected value is the one you worked by hand in Session 2.
  3. 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.

The life of a change requestSeven steps from draft to closed: draft, assess, authorize, scheduled, implementing, review, closed. Authorizing needs an implementation plan and a back-out plan; scheduling needs an approver other than the author and, for a PLC or HMI, a management-of-change reference. A change may end as rejected or failed. draftassessauthorizescheduledimplementingreviewclosedGate to authorize:an implementation planand a back-out planGate to schedule:the approver is not the author;a PLC or HMI needs a MOCreference firstEnds early:rejected at authorize,failed in implementingAll three change types (standard, normal, emergency) keep the same record and the same two gates in this build.
The life of a change request. No authorisation without both plans; no scheduling by the author or, for a PLC or HMI, without a management-of-change reference.
Configuration items and their relationshipsA press in the equipment list is linked to a PLC. An operator screen and a SCADA server connect to the PLC (connects_to is recorded from the item that uses the link to the item it talks to), a historian depends on the SCADA server, and the PLC depends on a network switch. A firmware change on the PLC affects the screen, the SCADA server and the historian. Press 3core_equipmentPLCplc · firmware changeNetwork switchnetwork_deviceOperator screenhmiSCADA serverscada_serverHistorianhistorianequipment_idconnects_toconnects_todepends_ondepends_onconnects_to is drawn from the item that uses the link to the item it talks to.Amber: the item being changed.Rose: items that depend on itor connect to it, found by arecursive query over relationships.
Who is affected by a PLC firmware change. The query follows depends_on and connects_to backwards and hosts forwards. The switch is something the PLC depends on, so it is not affected.
Step 10

Session 4: Resolve and survey, then a major incident, a problem and a PLC change

40 minutes

Why

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

Paste into Claude Code
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

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ ok 41 - resolve without a public reply is refused ok 42 - a second survey answer is refused ok 43 - authorize without backout_plan is refused ok 44 - schedule a plc change without ext.moc_ref is refused ok 45 - the author cannot schedule their own change ok 46 - a stale save (old row_version) is refused
1
⏺ Pull request #75 is green. Impact of CI-0001 (PLC press 3): HMI press 3, SCADA server, historian. The network switch is not affected. 6 refusals, each shown red first.2
The refusals are tests, each shown failing with its rule removed.
  1. Each rule is a test that tries to break it.
  2. The impact list goes into the change's impact analysis; check it against the drawing in this chapter.

You will see recreated screen

acme-platform-git-helpdesk-flows-acme-ops.vercel.app/desk/changes/CR-000001
CR-000001 · SYNTHETIC · PLC firmware 4.2 on press 3
Type and risknormal · medium
Statusauthorize
AffectedHMI press 3, SCADA server, historian1
Schedule
The PLC change on the preview, as approver.test, before the MOC reference is added.
  1. The impact list from the recursive query.
  2. 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

  1. RFC 5322: Internet Message Format (Message-ID, In-Reply-To, References). https://www.rfc-editor.org/rfc/rfc5322
  2. MDN: Intl.DateTimeFormat, time zones. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
  3. ISO/IEC 20000-1:2018 Service management system requirements. https://www.iso.org/standard/70636.html
  4. Giva: IT service desk software guide (ITIL 4 practices). https://givainc.com/blog/it-service-desk-software
  5. 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.
Moving out of the old toolExport from the old tool, map and report, then import with a dedicated login. Open tickets go live, closed tickets become archived history and articles become drafts. A rehearsal on the development project with a copy IT has approved, a comparison with the old tool's own figures, the final import into production through a workflow, and then the cancellation. Exporttickets, comments, users,organisations, articlesMap and reportstatuses, priorities, channels;nothing guessedImport loginrun twice = run once(legacy key is unique)Open ticketslive, original times keptClosed ticketshistory, archived_at setArticlesarrive as drafts to reviewRehearseIT-approved copy, devCompareold tool's figures vs yoursFinal importproduction, by workflowCancelafter the final export
From export to cancellation. Each step leaves something to check: counts that agree, a mapping with nothing guessed, an import that changes nothing the second time, and figures that match the old tool's own.
Old recordArrives asRule
Open ticket and its commentsLive svc_ticket and svc_ticket_message rowsOriginal created_at and sent_at kept; status mapped; private comments stay internal
Closed ticket before the history datesvc_ticket with archived_at setReadable and searchable; any update refused
Usercore_person (matched by address, or an external person with no sign-in)Doubtful matches listed for a person to decide
Organisationaccount_ref, by exact name, when the CRM module existsOtherwise empty and kept in ext
Articlesvc_kb_article, status draft, version 1The lead reviews and publishes; customer details removed first
Old ticket numberA legacy key in ext (for example freshdesk:1042), uniqueRunning the import twice adds nothing; replies quoting the old number thread
Step 11

Session 5: Map the old tool, and build an import you can run twice

40 minutes

Why

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:

Paste into Claude Code, then paste the old tool's names where it says
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

claude — acme-platform
⏺ Write(scripts/import/map.json)
+"status": { "Open": "open", "Pending": "pending_requester", "Waiting on Third Party": "pending_third_party",
+ "Resolved": "resolved", "Closed": "closed" },
+"unmapped": ["tag: urgent-legacy"]
1
⏺ Bash(npm test -- import)
⎿ ✓ second run: 0 inserted, 214 skipped (already imported) ✓ import login update: refused (insert-only) ✓ resolved with no reply: listed for the lead (1) ✓ workflow: unlisted sha256 refused; count mismatch fails
2
⏺ Pull request #78 is green. The fixture import is idempotent: the second run changes nothing. One tag is unmapped and listed for you to decide.3
The import is tested on a fixture export before it touches any project.
  1. The mapping is a file you can read and correct, not code.
  2. Run twice equals run once: the property the whole rehearsal depends on.
  3. 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.

Step 12

Session 5: Rehearse on the development project with an IT-approved copy, and compare a week

45 minutes

Why

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:

Email to IT
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.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Development Storage: a private bucket named imports; upload the redacted copy.

Open

https://github.com/acme-ops/acme-platform/settings/secrets/actions

GitHub: Settings, Secrets and variables, Actions: New repository secret.

Open

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

Paste into Claude Code
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

github.com/acme-ops/acme-platform/actions/runs/…
import-helpdesk · target development · mode write · from main
2
RecordExpected (approved)WrittenSkipped (reason)
Tickets open63630
Tickets closed (history)2,1402,1382 (spam, listed)
Comments11,80211,79012 (on the 2 spam tickets)
Users4184180
Articles57570
The workflow run on the development project: the count table is the check.
  1. A green run means the file was the approved one and every count matched. Read the table anyway.
  2. Every skipped row has a reason, and the reasons add up.

You will see recreated screen

github.com/acme-ops/acme-platform/blob/helpdesk/rehearsal/docs/cutover.md
Last full week: old tool against platform
1
MeasureOld tool (report)PlatformDifference explained
First response, median1 h 52 m (SLA report)1 h 52 mnone
Time to resolution, median14.0 h13.1 hold tool counts the pending status; ours pauses it
SLA attainment88%88%none
The side-by-side table in docs/cutover.md: the old tool's own figures beside the platform's for the same week.
  1. 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.

Step 13

Session 6: The final import into production, through the pipeline

45 minutes

Why

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:

Open

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.mjs on 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.
Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Vercel: set SVC_EMAIL_MODE, then redeploy production from the Deployments page.

Paste into Claude Code, then paste the run's count table
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

github.com/acme-ops/acme-platform/actions/runs/…
import-helpdesk · target production · mode write · from main
Export sha2569f2c…e41a · listed in docs/imports/helpdesk-approved.md (approved by sam@acme.com)1
The production run, started by you from main, checks the export against the line owner two approved.
  1. No one person can write real records into production: the file must be the one owner two approved in a merged pull request.
  2. 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.

Step 14

Session 6: Retire the old tool, switch the importer off, and record the saving

30 minutes

Why

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:

Paste into Claude Code
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.
Open

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

claude — acme-platform
⏺ Write(docs/cutover.md)
+## Saving (from invoices)
+Old tool: <from the invoice, with its number and date>
+Module running cost: no new service; email sending as billed by the provider
+Old tool cancelled on <date>; final export stored in the records store.
1
⏺ Pull request #84 is green. docs/helpdesk-inventory.md marks 5 channels replaced and 1 still on the old way (the walk-up desk), with today's date.2
The record of the retirement: what was replaced, and the saving from invoices.
  1. Every figure carries the invoice it came from; no estimate.
  2. 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.

Before you go on · The module is done whenTick each one

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

  1. Freshdesk API documentation. https://developers.freshdesk.com/api/
  2. Zendesk Developer Docs: Ticketing API. https://developer.zendesk.com/api-reference/ticketing/introduction/
  3. GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
  4. 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

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. Where do the old tool's figures in docs/helpdesk-inventory.md come from?
2. Why is svc_ticket.requester_contact_ref a soft link?
3. Why are the four hand-worked tickets a test fixture and not part of the seed?
4. Who applies the module's migration to the development project?
5. The clock's update to svc_sla_event reports success but nothing changes. Why?
6. Where does a right that a later step needs get added?
7. A customer's reply has a rewritten subject with no ticket number. What finds its ticket?
8. With SVC_EMAIL_MODE set to off, what should a ticket show for the acknowledgement?
9. Business hours 09:00–17:00 on weekdays, Monday 2026-05-25 a holiday. Ticket B arrives Friday 15:00 with a 240-minute first-response target. When is it due?
10. Who can schedule a normal change on a PLC that has both plans?
11. What makes the import safe to run twice?
12. How does the final import reach production?