Skip to content

Help Assistant Developer Guide

Ed Mozley edited this page Nov 11, 2026 · 11 revisions

πŸ› οΈ The help assistant - Developer Guide

How the help assistant works under the hood. The plan, the decisions and the reasoning are on The help assistant - design; this page covers what is built.

Step What State
1 One shared embedding file βœ… Embeddings - Developer Guide
2 The help index and word search βœ… this page
3 System β†’ Help assistant and the window (no-AI level) βœ… section 7
4 Vectors not yet
5 Ask - the written answer not yet
6 Unanswered questions not yet

For users: The help assistant.


The shape of it

File What it does
includes/help_index.php The pages, reading a rendered page, building the index, the search
scripts/help_render_page.php Renders ONE help page in ONE language and prints its sections as JSON
scripts/help_index_build.php Builds or refreshes the index from the command line
help_sections The index - only a cache of the help, one row per section per language
includes/i18n.php I18n::pinLocale() - fixes the language for a command-line render
tests/help-search.php, tests/help-search-questions.php The search tests, and the question set every step is measured against
includes/help_assistant.php Who may use it, the reply and its canned line, the conversation, the index status, starting a rebuild
includes/help_assistant_widget.php The header button and the window's config, drawn by renderHeaderRight()
assets/js/help-assistant.js, assets/css/help-assistant.css The window
api/help_assistant/{ask,history,reset}.php The window's endpoints
system/help-assistant/index.php, api/system/help_assistant.php System β†’ Help assistant
help_assistant_messages, analysts.help_assistant The conversation; who has it
tests/help-assistant.php Step 3's tests
php scripts/help_index_build.php                   # English
php scripts/help_index_build.php --locales=de,es   # plus German and Spanish

1. What a section is - the house-style markup

Every help page already marks its sections the same way, so that markup is the contract - no new markup was needed:

<div class="help-section" id="settings" data-cap="TICKETS_SETTINGS" data-help-search="off">
    <div class="help-section-header">
        <span class="help-section-num">10</span>
        <div><h3>Settings</h3> <p>...</p></div>
    </div>
    <div class="help-cards">
        <div class="help-card"><strong>Departments</strong><span>Create departments like IT...</span></div>
    </div>
</div>
Part Becomes
id the anchor an answer links to - tickets/help.php#settings
the first <h3> the title
everything inside the text, kept as blocks - one per paragraph, card, step, note, list item, table row
data-cap (optional) the capability (Cap enum) the section describes - for permission-aware answers in step 5
data-help-search="off" (optional) never indexed

The number badge, <script> and <style> are left out. A section without an id is ignored.

Plus one entry for the page's introduction - its .help-hero banner and any .help-lede paragraph outside the sections, titled by the hero's (or the page's) <h2>. It has no anchor (section_key is the page itself), so it links to the top of the page, and it is often the best answer to "what is X?". An audit of all 74 pages (November 2026) found no section without an id and no help text outside a section other than these introductions. This is written into Help page house style, and tests/help-search.php fails if any help page gives no sections.

data-cap is read and stored now; the marks themselves go onto the pages with step 5, when answers start using them.


2. Rendering, not reading the source

The obvious approach - read each page's source for t('...') keys - does not work:

  • Many pages build their sections in a loop through helpers ($h($id . '.title') in people/help.php), so the keys never appear literally.
  • The System help pages are English in the page itself, with no keys at all.

So every page is rendered, exactly as a reader would see it, and the sections are read out of the HTML (helpRenderSections(), using DOMDocument).

One process per page

function helpIndexRenderPage(string $root, string $php, string $page, string $locale, int $analystId): ?array
{
    $cmd = escapeshellarg($php) . ' ' . escapeshellarg("$root/scripts/help_render_page.php") . ' '
         . escapeshellarg($page) . ' ' . escapeshellarg($locale) . ' ' . (int)$analystId;
    exec($cmd . ' 2>' . (stripos(PHP_OS_FAMILY, 'Windows') === 0 ? 'NUL' : '/dev/null'), $out, $code);
    // ...the last non-empty line is the JSON
}

TRAP: never render two help pages in one PHP process. Pages define functions and constants, call session_start() and may exit() - the second would collide with the first, or never run. help_render_page.php renders one, prints JSON from a shutdown function (so it is printed even when the page exits), and ends.

The renderer gives the page an ordinary signed-in GET:

I18n::pinLocale((string)$locale);                      // the page's own initFromSession() cannot change it
session_id('helprender' . bin2hex(random_bytes(8)));   // a throwaway session, destroyed at the end
session_start();
$_SESSION['analyst_id'] = (int)$analystId;
parse_str($query, $_GET);                              // system/integrations/help.php?provider=jira
ob_start();
register_shutdown_function(function () {
    $html = '';
    while (ob_get_level() > 0) $html = ob_get_clean() . $html;
    @session_destroy();
    echo "\n" . json_encode(['ok' => true, 'sections' => helpRenderSections($html)], ...) . "\n";
});
chdir(dirname("$root/$page"));
require "$root/$page";
  • The analyst is an active administrator with every module (helpIndexRenderAnalyst()), only so each page's own requireModuleAccess() lets it through. Nothing is written for them - help pages do not touch the Recent trail.
  • The language: a page calls I18n::initFromSession(), which reads the analyst's saved preference. I18n::pinLocale() - command line only, it does nothing in a web request - makes that call leave the locale alone.
  • It is command-line only (PHP_SAPI !== 'cli' β†’ 404), and the page argument must match the help-page pattern, so it cannot be pointed at anything else.

Which pages

helpIndexPages(): every */help*.php and */*/help*.php that calls requireModuleAccess('...') (its module), every system/help/*.php except _*.php and index.php (module system), plus HELP_INDEX_EXTRA - the integrations guide, one page per ?provider=, which the folder scan cannot find. Left out on purpose (HELP_INDEX_EXCLUDE): the self-service portal's guide and Help Centre, which are for requesters. Today: 74 pages, 712 entries - 639 sections plus 73 page introductions.


3. Building the index

helpIndexBuild($conn, $locales) renders every page in English, then each extra language:

Unchanged section left alone - its row, and later its vector, are kept (text_hash matches)
Changed section updated
Section gone from its page deleted; a page that no longer exists takes its sections with it
Another language stored only where the text differs from the English - an untranslated section would be a second copy of the English, so the System help pages (English in the page) never get "German" rows
A module switched off skipped, its rows left alone - nobody can open it, so the search never returns them

An unchanged rebuild changes nothing (tested). English takes about 25 seconds for 74 pages; English, German and Spanish about 80.

help_sections:

CREATE TABLE IF NOT EXISTS `help_sections` (
    `section_key`      VARCHAR(191) NOT NULL,   -- 'tickets/help.php#settings'
    `locale`           VARCHAR(10) NOT NULL DEFAULT 'en',
    `page`, `anchor`, `module`, `cap`, `title`, `body`,
    `text_hash`        CHAR(64) NOT NULL,       -- sha256 of title + body: what it says now
    `embedding`        MEDIUMTEXT NULL,         -- step 4
    `embedding_hash`   CHAR(64) NULL,           -- the text_hash the vector was made from
    `embedding_model`  VARCHAR(80) NULL,
    `source`           VARCHAR(20) NOT NULL DEFAULT 'built',   -- or 'release'
    `source_version`   VARCHAR(20) NULL,
    `built_datetime`   DATETIME NOT NULL,
    UNIQUE KEY `uq_help_sections_key_locale` (`section_key`, `locale`),
    KEY `idx_help_sections_locale_module` (`locale`, `module`)
);

embedding_hash is how the out-of-date warning will work: a section whose text_hash is not its embedding_hash has changed since its vector was made.


4. The word search

helpSearch($conn, $analystId, $question, $locale, $currentModule) = helpRank(helpSectionsFor(...), ...).

Which sections - helpSectionsFor()

Every section in the analyst's language where there is one, otherwise its English row - the fallback is per section, so a half-translated language never hides the other half. Then only modules the analyst can open (analystCanAccessModule(), which also says no to a module switched off for the install).

Search words - helpTokens() and helpStem()

Lower case; letters and digits only; common English words dropped (how, do, I, a, the...); then a cut-down Porter stemmer. It only has to be consistent - the question and the help go through the same rules - not produce real words:

In Out
departments department
categories category
statuses, status status
adding, added, adds, add add
settings, setting set
create, created, creating creat
route, routing rout
breached breach
class, analysis, business unchanged

Non-English words are only lower-cased.

Ranking - BM25 over passages

BM25 is the classic search-engine scoring. For each question word t in a passage d:

$$\text{score} = \sum_t \text{idf}(t)\cdot\frac{f(t,d),(k_1+1)}{f(t,d)+k_1\left(1-b+b,\frac{|d|}{\text{avg}|d|}\right)},\qquad \text{idf}(t)=\ln!\left(1+\frac{N-n_t+0.5}{n_t+0.5}\right)$$

with k₁ = 1.2 and b = 0.75. In words: rare words count for more (ticket is in most sections and says little; department narrows it right down), a word appearing more often helps but with diminishing returns, and a long passage does not win just by being long. Title words count three times (HELP_TITLE_WEIGHT).

TRAP: score passages, not whole sections. The first build scored whole sections, and the very first test question - how do I create a ticketing department - missed. Tickets β†’ Settings is about 10,000 characters of cards (the average section is 1,500), and BM25's length rule, correctly, buried its one Departments card. Now each section is cut into passages of about 700 characters made of whole blocks (helpPassages() - the renderer's blank-line-separated blocks, packed in order, never splitting a card), passages are scored, and a section scores as its best passage, with that passage as the snippet.

foreach ($sections as $i => $s) {
    $titleTokens = helpTokens($s['title']);
    foreach (helpPassages($s['body']) as $text) {
        $tokens = array_merge(...array_fill(0, HELP_TITLE_WEIGHT, $titleTokens), ...[helpTokens($text)]);
        // ...term frequencies, document frequencies over PASSAGES
    }
}
// ...each section keeps its best passage's score
if ($currentModule !== null && $s['module'] === $currentModule) $score *= HELP_MODULE_BOOST;   // 1.15 - a tie-breaker

About 80 ms over 712 entries on a laptop, all in PHP.


5. How good it is - the question set

tests/help-search.php holds 65 realistic questions, each with every section that would be a right answer, scored as is a right section in the top 5:

Kind Example Word search
Plain how do I create a ticketing department 43/47 (91%) - floor 80%
Exact names Warbot, MoSCoW, Enforce approvals 6/6 (100%) - floor 80%
Vague - no words shared with the answer my boss wants a weekly PDF of how we are doing 2/6 (33%)
Other languages Wie erstelle ich eine Abteilung?, Hogyan hozzak lΓ©tre jegykezelΕ‘ rΓ©szleget? 2/6 (33%)

Plain and exact questions must stay above their floor. Vague questions and other languages are reported, not failed - they are exactly what vectors (step 4) and the AI's own searching (step 5) are for, and these numbers are the baseline those steps have to beat. Typical misses, and why:

  • my boss wants a weekly PDF β†’ the answer is Report packs; no word in common.
  • Wie erstelle ich eine Abteilung? β†’ the German help says Abteilungen; there is no German stemming.
  • Restablecer la contraseΓ±a de un analista β†’ the answer is System help, which is English only.
  • Hungarian and Polish β†’ no help in those languages, so no words to match at all.

6. Tests

tests/help-search.php:

  • No database (19 checks): reading sections from rendered HTML (only sections with an id, the page's introduction, the h3 title without the number badge, a card's title not glued to its body, scripts left out, data-cap, data-help-search="off"); search words and the stemmer; passages made of whole blocks of at most 700 characters; one card in a very long section winning, with that card as the snippet; the module tie-breaker.
  • With FREEITSM_TEST_DATABASE: builds English, German and Spanish through the real renderer; every help page gives sections; every section has a title; German rows only where the text is German (none for System help); an unchanged rebuild changes nothing; a ZZ analyst with only Tickets is searched over Tickets help only (control: an administrator gets every module); then the question set.
php tests/help-search.php
FREEITSM_TEST_DATABASE=<the throwaway db> php tests/help-search.php

See also Developer Tests - Knowledge.


7. Step 3: the window and System β†’ Help assistant

Who has it

Two switches, both needed: help_assistant_enabled = '1' in system_settings (System β†’ Help assistant, off by default) and analysts.help_assistant = 1 for the analyst (ticked on the same page). helpAssistantAllowed() asks both, plus active, once per request - the header asks on every page:

function helpAssistantAllowed(PDO $conn, int $analystId): bool
{
    static $cache = [];
    if (isset($cache[$analystId])) return $cache[$analystId];
    if ($analystId <= 0 || !helpAssistantReady($conn) || !helpAssistantEnabled($conn)) return $cache[$analystId] = false;
    $st = $conn->prepare("SELECT 1 FROM analysts WHERE id = ? AND help_assistant = 1 AND COALESCE(is_active, 1) = 1");
    ...
}

TRAP: the header must not break before Database Verify. helpAssistantReady() checks the column and tables exist; until they do, the assistant is simply absent. helpAssistantWidgetRender() also swallows any error and draws nothing - a help button is never worth an error on every page.

The three window endpoints share one gate, helpAssistantRequireJson(): signed in (401), allowed (403). They are not a module, so tests/module-access-coverage.php lists api/help_assistant/ with that reason; the search itself only returns modules the analyst can open (helpSectionsFor()).

The header button

renderHeaderRight() (includes/waffle-menu.php) - the header on every module - calls helpAssistantWidgetRender($GLOBALS['current_module'] ?? null). When allowed it prints the button, links the CSS, and hands the window its config:

window.HELP_ASSISTANT = {
    ask, history, reset,        // endpoint URLs from BASE_URL
    module: 'tickets',          // the page's module - a search tie-breaker
    strings: { title, greeting, placeholder, ... }   // help_assistant.* in the analyst's language
};

The reply

api/help_assistant/ask.php β†’ helpAssistantAnswer(): helpRank() over helpSectionsFor() in the analyst's language, each result given its page's title (from that page's introduction entry) and a link from BASE_URL. Then the kind of reply, which picks the line:

function helpAssistantReplyKind(array $results, ?string $currentModule = null): string
{
    if (!$results) return 'none';
    $top = (float)$results[0]['score'];
    if ($top < HELP_ASSISTANT_WEAK_SCORE) return 'weak';                       // 9.0
    $second = isset($results[1]) ? (float)$results[1]['score'] : 0.0;
    if ($second <= 0.0 || $top >= HELP_ASSISTANT_CLEAR_RATIO * $second) return 'clear';   // 1.25
    if ($currentModule !== null && ($results[0]['module'] ?? null) === $currentModule) return 'module';
    return 'several';
}

The thresholds come from the question set, not a guess. Printing every question's top score and its lead over the runner-up: of the 22 questions whose top result was at least 1.25 times the next, 20 had a right section first and one more had it in the top five - so "this looks like exactly what you need" is honest about nine times in ten. Below a top score of 9 sat most of the shaky answers, where "these might be close" is the right tone even when it is right.

helpAssistantPhrase($kind) picks at random from help_assistant.phrase.<kind>.1, .2, ... - as many as the language file has; English fills any a language lacks. A test checks no line claims an AI read anything.

The conversation

help_assistant_messages: one row per message - role (user / assistant), body, and for a reply results as JSON ({kind, results}), so history redraws exactly what was shown. The newest 200 per analyst are kept. Reset deletes the analyst's rows. The table has a cascading foreign key to analysts and is registered in analystReferenceRegistry() as personal.

The window

assets/js/help-assistant.js builds the window on first open - everything with textContent, since questions and help text are data:

  • Desktop: fixed, bottom right by default, dragged by its header (pointer events, clamped below the header and inside the viewport). Position and open are a per-viewer convenience in localStorage (try/catch - private mode just forgets). Open on one page, it reopens on the next.
  • Phone (≀ 768px): a full-screen sheet; place() clears any desktop position so the CSS wins without !important; 16px text so iOS does not zoom (Mobile Techniques Β§3); opening pushes a history entry, so the device back button closes it; never reopened by itself, because it would cover the page just opened.
  • Opening a result scrolls the help panel, never the page (#2774). Help pages scroll inside .help-main; a plain #anchor made the browser scroll the page too, sliding the header up about 14px. A result on the same page (samePage(), which ignores .php for pretty URLs) scrolls only its panel and updates the hash with replaceState; one on another page leaves a jump note in localStorage, and that page, once loaded, puts the page back at the top and scrolls its panel to the section - the help pages' own section links do the same.
  • Classes are hlpa-. It is loaded on every page, beside every module's CSS - System β†’ Help assistant itself uses ha-.

System β†’ Help assistant and the index

The page opens with a green panel saying it works without any AI, before the switch, the per-analyst list (All / None / a filter) and the index panel. Saving with the assistant on and no index yet starts a build, so the window is never answering "nothing found" to everything.

Rebuild spawns scripts/help_index_build.php with the Intune worker's intuneSpawnGenericWorker() (reused, not copied). The build writes its progress to help_index_build_state (running / done / failed, with stats), which the page polls every four seconds; a running older than half an hour counts as dead. With no --locales, it builds English plus every language analysts have chosen (helpIndexLocalesInUse()). The changed since warning is the quick check: any help page or language file newer than the last build.

TRAP: a background worker must not print. intuneSpawnGenericWorker() pclose()s the worker's output straight away. On Windows the first write to that closed pipe killed the build after one page - it said running for ever. Started with the job id 0, the builder now prints nothing; progress goes to the setting.

TRAP: the renderer's one expected notice. Each page's own session_start() is ignored because the renderer's session is already running, and PHP logs a notice per render - 74 per language per build. help_render_page.php silences exactly that notice and nothing else.

Tests

tests/help-assistant.php - 12 checks without a database (the reply kinds at the thresholds; every kind has wording in English, German and Spanish; a German asker gets German; the lines vary; none claims an AI read anything) and 20 over HTTP with a ZZ administrator and a ZZ analyst made for the run: the settings are admin-only; off by default, the window refuses and the header draws no button; saving switches it on for exactly who is ticked; the button appears with the page's module; asking returns a line and results with a right answer; nothing found gives the none line; an empty question is refused; a non-admin gets no System help; history oldest first; Reset; and a background rebuild that finishes on its own (about 22 seconds). The switch and every analyst's flag are restored in finally.

The window itself was driven in headless Chrome at 1280 and 390 pixels wide: it opens bottom right (desktop) or full screen with 16px text (phone), nothing scrolls sideways, a question returns four cards with Tickets help β†’ Settings first, and Reset brings the greeting back.


Related

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally