feat(kit): the engagement contract, taught and built (cutover 5 of 7)
All checks were successful
PR Checks / prose (pull_request) Successful in 7s
PR Checks / template (pull_request) Successful in 31s

The kit was pinned to website 963d734 -- MODULE_API 1.6.0, the Teams cutover --
and the platform is on 1.9.0. Three registrations and two calls arrived in
between, and a reader building against this book would have found no mention of
any of them: a module can now declare what its game can announce, and never who
is told.

Moving `ci/core-ref.json` is the mechanism for exactly this. The pin is now
66bb3b9a (website `main`, the engagement cutover) and `template/module.json`
declares `^1.9.0`.

What chapter 2 gained, under "Telling core something happened":

  * a TRIGGER is a payload contract, not a notification stream -- the two share
    one id namespace and are constantly confused;
  * `ceiling` is required, has no default, and is a CONTAINMENT tree rather than
    a size ladder (a `staff` ceiling does not permit `owner`);
  * an AUDIENCE resolver returns user ids and nothing else, resolves to NOBODY
    on failure, and takes CONSTANT params -- the constraint worth knowing before
    you design around it;
  * templates re-ensure per seedVersion, rule groups are offered ONCE per group
    key, so a rule appended to an existing group reaches fresh installs only;
  * `ctx.events.emit` binds the owner and is fire-and-forget; `ctx.inbox.push`
    is the direct write, for when there is nothing for an operator to decide.

The template builds all of it: one trigger, one audience over the clan roster it
already had, one seeded body and one seeded rule group, and an emitter in
`boot.js` that fires on the TRANSITION rather than on the poll. Seven new tests,
including the audience that resolves to nobody when its query throws.

Three claims were wrong and are corrected here rather than shipped:

  * core validates `subjectKey` against the declared variables and refuses the
    module; the draft taught a cooldown keyed on `undefined`, which the check
    exists to prevent and a reader will never see.
  * `emit` throws OUTSIDE production and only drops-and-logs inside it. Teaching
    the second half alone leaves a developer meeting a throw the book says
    cannot happen.
  * the seeded body itself was malformed -- heading `level: 2` where the block
    registry takes 'h2', and no block ids at all.

The third is the one worth keeping: `registerEngagementSeeds` checks that
`blocks` is a non-empty array and stops, so that body would have registered,
seeded, and failed the first time an operator opened it. Found by running the
template's `register()` through core's real registry at the pinned ref -- which
CI does not do, and cannot: the template job checks the version and runs the
template against fakes. A fake accepts what core refuses. The gap is now named
in the chapter, beside the code, and in the pin's own comment, and the rule that
bit has a test that fails on it.

Also: `checkLinks` skipped `.core/`. Bumping this pin means cloning core into
that directory first, and the walk then reported nine broken links in someone
else's README. CI never saw it -- the clone happens in the `template` job and
the check runs in `prose` -- so it was a failure only a person could meet.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 12:57:55 -05:00
parent 39736f8448
commit a8fa524263
12 changed files with 597 additions and 27 deletions

View File

@@ -52,7 +52,45 @@ async function refresh() {
try {
// A real module calls its sidecar's REST API here. Two hardcoded values
// stand in, so that the page renders and the seam is visible.
await worldStatusDb.setStatus({ online: true, players: 0, worldName: 'Example World' })
const next = { online: true, players: 0, worldName: 'Example World' }
// ── Emitting a declared event ──────────────────────────────────────────
//
// **Emit on the TRANSITION, not on the poll.** This function runs every
// thirty seconds; a rule on an event fired every thirty seconds is a rule
// that mails somebody every thirty seconds. Core has a cooldown and an
// hourly cap and they would both hold, but leaning on them means the module
// is emitting "the world is still up" and calling it news. Read the previous
// state, compare, and emit only when the answer changed.
//
// The read is BEFORE the write for the same reason, and getting that
// backwards is the easy version of this bug: after `setStatus` the previous
// value is gone and every poll looks like no change at all — an emitter that
// never fires and never errors.
const previous = await worldStatusDb.getStatus()
await worldStatusDb.setStatus(next)
// `previous === null` is the first boot on a fresh install, not a change.
// Treating it as one would announce the world coming online to everyone the
// first time an operator started the site.
if (previous && Boolean(previous.online) !== next.online) {
// Fire-and-forget: no await, no return value, nothing to handle. Core
// validates the payload against what `index.js` declared, and what a
// mismatch does depends on where you are running. **In production it is
// dropped and logged** against this module, because a notification must
// never be able to break the thing it is about. **Anywhere else it throws**,
// at this line, so the stack points at your own call instead of at a
// warning nobody reads. Neither is a condition to catch: a payload that
// does not match the contract you declared is a bug to fix.
core.emit('examplegame.world.status_changed', {
data: {
worldName: next.worldName,
status: next.online ? 'online' : 'offline',
players: next.players,
url: '/world',
},
})
}
} catch (err) {
log.warn('could not refresh world status', { error: err.message })
}

View File

@@ -91,6 +91,21 @@ module.exports = {
// stack. Routers are built inside `register()`, so `ctx` is set by then.
get middleware() { return need().middleware },
// Firing a declared event (MODULE_API.md §2.3). Wrapped as a call rather than
// exposed as `get events()`, so that `require('../core').emit` taken at file
// scope still resolves `ctx` at call time like everything else here.
//
// **It returns nothing, and in production it never throws at the caller.** The
// emit is the end of this module's involvement: core validates the payload
// against the declared contract, decides which rules match, resolves who they
// reach and sends. A module cannot address a person, choose a channel or write
// a subject line, and this seam is deliberately too narrow to try (§2.7).
//
// Outside production a bad payload throws here rather than being logged, which
// is the point: you meet the mismatch in your own tests instead of in an
// operator's log six weeks later.
emit: (triggerId, envelope) => need().events.emit(triggerId, envelope),
// Deployment facts. `moduleRoot` is the absolute path to `modules/<id>/` — the
// only correct way to find a file you shipped, because the working directory is
// core's and the module's location is the loader's business.

View File

@@ -103,6 +103,165 @@ module.exports = function register(ctx, api) {
// optional ones is an edit to the provider and not to this file.
api.registerTeamProvider(clanProvider)
// ── Engagement: declaring what your game can announce ────────────────────
//
// The three calls below are one seam, and it is the one where a module is most
// tempted to reach past the boundary. **You declare what CAN happen; core
// decides who is told.** A module never names a person, a channel or an
// address, and never sends anything (MODULE_API 1.7.0 and 1.9.0; §2.7).
//
// A TRIGGER is not a notification stream, and the two are easy to confuse
// because both are catalogs of things that happen. A stream is a subscribe
// toggle you publish to yourself. A trigger is a PAYLOAD CONTRACT an operator
// writes rules against — it says what variables the event carries and how wide
// an audience it may ever be given, and core does the sending. Their ids share
// one namespace, so declaring both for one id is legal and is one event with a
// toggle and a contract; taking an id another module owns is not.
api.registerEventTriggers([
{
id: 'examplegame.world.status_changed',
label: 'World came up or went down',
description: 'The game server changed between online and offline.',
kind: 'event',
// The cooldown subject: "once per world", not "once per user". It must
// NAME one of the variables below — core refuses the registration
// otherwise, with this trigger's id in the message, and the module does not
// load. That check exists because the failure it prevents is silent: a
// subjectKey naming nothing keys every subject on `undefined`, which looks
// exactly like the feature working right up until two worlds share it.
subjectKey: 'worldName',
audience: 'authenticated', // what a rule is CREATED with
// ...and the widest it may EVER be given. Required, with no default,
// because there is no safe value to guess: `owner` would silently break a
// broadcast and `authenticated` would silently widen a staff-only event.
// The values are ordered by CONTAINMENT, not by size — see chapter 2.
ceiling: 'authenticated',
version: 1,
variables: [
// Every variable needs an `example`, and it is not decoration: it is what
// lets an operator preview and test-send a template without waiting for a
// real game event, which is the reason template systems ship untested.
{ name: 'worldName', type: 'string', required: true, example: 'Example World' },
{ name: 'status', type: 'string', required: true, example: 'online' },
{ name: 'players', type: 'int', required: false, example: 42 },
// A `url` is validated SITE-RELATIVE, because it ends up in an href in a
// mail somebody opens days later. Never a full URL of your own.
{ name: 'url', type: 'url', required: false, example: '/world' },
],
},
])
// An AUDIENCE is a named set of PEOPLE this module can resolve over its own
// data, for an operator to point a rule at. "This clan's members" is one;
// "everyone who opened the last mail" is not, and nothing here builds it.
//
// **The resolver returns user ids and nothing else.** It is not handed a
// template, a channel or an address and it cannot enumerate them — core maps
// ids to addresses on its own side, after preferences, suppression and the
// verification gate. That is what stops this becoming the back door §2.7 spends
// a section closing.
//
// Audiences are their OWN id space, unlike triggers and streams: an audience
// names a set of people and a trigger names an event, so the two may share a
// name without colliding.
api.registerAudiences([
{
id: 'examplegame.clan.members',
label: 'Members of a clan',
// `int` or `string` only, and CONSTANT — an operator fills these in when
// they save the rule. There is no way to say "the clan this event was
// about"; if a rule needs that, the EVENT carries its own recipients
// instead. Finding that out late is a phase's worth of rework.
params: [{ id: 'clanId', type: 'string', required: true }],
ceiling: 'members',
resolve: async ({ clanId }) => clanProvider.listClanMemberUserIds({ clanId }),
},
])
// Finally the CONTENT: the bodies your messages use, and the rules that decide
// when one is sent. Both arrive **switched off** — `enabled` is not a parameter
// and there is no call that sets it. An operator turns a module's mail on;
// installing a module never does.
//
// The two halves have different lifetimes, and the asymmetry is the contract:
//
// • **Templates are re-ensured on every boot**, under `seedVersion`, so
// improving a default body reaches deployments that never edited it — and
// one an operator HAS edited is marked customized and left alone. Bump
// `seedVersion` when the body changes; never for a comment.
// • **Rule groups are offered ONCE, per named group key.** Re-offering would
// resurrect a rule an operator deleted and reset one they enabled. So a rule
// appended to an existing group reaches FRESH INSTALLS ONLY. That is the
// guarantee rather than a limitation to work around: a rule that has to
// reach existing deployments takes a NEW group key, and you choose that
// knowingly because you name the groups.
//
// Core's generic bodies are a first-class answer, not a fallback: point a
// channel at `notify.event` / `inapp.event` / `notify.digest` and author
// nothing. Ship a body of your own when the message has something to say that a
// structural projection of the payload cannot. Below, the mail does — a world
// coming back deserves a sentence — and the in-app item does not, so it uses
// core's.
//
// Note the two casings, which are not a slip: a TEMPLATE is an object this call
// shapes (`triggerId`), and a RULE is a row (`trigger_id`). Copy them as they
// are.
api.registerEngagementSeeds({
templates: [
{
// MUST be namespaced `<moduleId>.` — the key column is unique across the
// whole table, and an unprefixed `notify.event` from a module would
// collide with core's own body and win.
key: 'examplegame.world-status-changed',
name: 'World — status changed',
channel: 'email',
subject: '{{worldName}} is {{status}}',
triggerId: 'examplegame.world.status_changed',
triggerVersion: 1,
seedVersion: 1,
// The same block objects the template editor writes, so an operator can
// open this in the admin panel and keep editing from here.
//
// **This is the one thing in this file core does not check for you.**
// `registerEngagementSeeds` asserts that `blocks` is a non-empty array and
// stops; the BODY is validated by the block registry, which runs in the
// editor and in the renderer. So a malformed block registers, seeds, and
// first shows itself when an operator opens the body or a rule fires.
// Two that are easy to get wrong: every block carries its own `id`, and
// `email.heading`'s `level` is 'h1' | 'h2' | 'h3' — not a number.
blocks: [
{ id: 'h', type: 'email.heading', props: { level: 'h2', text: '{{worldName}} is {{status}}' } },
{ id: 'intro', type: 'email.text', props: { text: 'There are {{players}} players online right now.' } },
{ id: 'cta', type: 'email.button', props: { label: 'Open the world page', url: '{{url}}' } },
],
},
],
ruleGroups: [
{
key: 'world-v1',
note: 'the world status rule, seeded once',
rules: [
{
trigger_id: 'examplegame.world.status_changed',
name: 'World status changes',
audience: 'authenticated',
channels: ['email', 'inapp'],
template_keys: {
email: 'examplegame.world-status-changed',
inapp: 'inapp.event',
},
// Two ceilings on volume, and they answer different questions. The
// cooldown is per SUBJECT — one mail per world per hour, however many
// times it flaps. The hourly cap is per RULE, and is the thing that
// keeps a misconfiguration from becoming a mail storm.
cooldown_seconds: 3600,
max_sends_per_hour: 200,
},
],
},
],
})
// The lifecycle hooks (§2.5). `onBoot` runs after core's schema, after this
// module's schema fragment, and BEFORE the HTTP listener binds — so a module
// that must not serve traffic until it has warmed a cache gets that for free.

View File

@@ -82,4 +82,25 @@ async function replaceClan({ externalId, name, abbr, memberCount, members }) {
}
}
module.exports = { listClans, findClan, listMembers, replaceClan, CLANS, MEMBERS }
/**
* The site accounts behind one clan's roster — the whole of an audience resolver.
*
* `user_id` is NULL for most characters, and the filter is the point: an audience
* resolves to PEOPLE WITH ACCOUNTS, and a character nobody has linked is not one.
* Returning its NULL would hand core a hole in an array it is about to mail.
*
* DISTINCT because one person may hold several characters in the same clan, and
* the resolver's contract is a set of users rather than a list of characters.
* Without it a three-character player is told three times.
*/
async function listMemberUserIds(clanId) {
const rows = await core.query(
`SELECT DISTINCT user_id AS userId
FROM ${MEMBERS}
WHERE clan_id = ? AND user_id IS NOT NULL`,
[clanId],
)
return rows.map((r) => r.userId)
}
module.exports = { listClans, findClan, listMembers, listMemberUserIds, replaceClan, CLANS, MEMBERS }

View File

@@ -292,6 +292,36 @@ async function projectRoster(externalId, members, viewer) {
// a page that does not exist, which is worse.
const pageUrlTemplate = '/examplegame/clans/{externalId}'
// ── The audience resolver ─────────────────────────────────────────────────
//
// Registered in `index.js` as `examplegame.clan.members` and called by core when
// a rule pointed at that audience fires. It lives beside the provider because it
// answers a question about the same rows, and it is NOT part of the provider —
// core calls it through the audience registry, not through the five members
// above.
//
// **Three rules, and every one of them protects somebody's mailbox rather than
// this module's correctness.**
//
// 1. Return user ids and nothing else. You are not handed a template, a channel
// or an address, and you may not enumerate them; core maps ids to addresses
// on its own side, after preferences, suppression and the verification gate.
// 2. Never widen on failure. A resolver that cannot answer returns the EMPTY set
// — never "everyone", never the last good answer. Core treats a throw the
// same way, but doing it here is what lets the log say which clan.
// 3. It is a SET of people, not a list of characters. The `DISTINCT` is in the
// query for that reason (see `clanProvider.db.js`).
async function listClanMemberUserIds({ clanId }) {
try {
return await db.listMemberUserIds(clanId)
} catch (err) {
log.warn('could not resolve clan members; resolving to nobody', {
clanId, message: err.message,
})
return []
}
}
module.exports = {
getTeams,
getTeamMembers,
@@ -300,4 +330,5 @@ module.exports = {
rosterVisibleTo,
pageUrlTemplate,
gameIsReachable,
listClanMemberUserIds,
}

View File

@@ -49,6 +49,11 @@ function fakeCtx(overrides = {}) {
return log
},
auth: { getUserFromRequest: spy(null) },
// The engagement seam (§2.3). One method, recording, because that is the
// whole of what a module may do with it: fire a declared event and stop.
// Core's own emit is fire-and-forget and returns nothing, so this does too —
// a fake that returned a receipt would invite a module to wait on one.
events: { emit: spy(undefined) },
middleware: {
requireAuth: (req, res, next) => next(),
requireRole: () => (req, res, next) => next(),
@@ -85,7 +90,10 @@ function fakeCtx(overrides = {}) {
* an operator's install.
*/
function fakeApi() {
const record = { routes: null, extensions: [], streams: null, legs: [], hooks: {}, teamProvider: null }
const record = {
routes: null, extensions: [], streams: null, legs: [], hooks: {}, teamProvider: null,
triggers: null, audiences: null, engagementSeeds: null,
}
const called = new Set()
const once = (name) => {
if (called.has(name)) throw new Error(`${name}() called twice`)
@@ -103,6 +111,9 @@ function fakeApi() {
// module registering a provider collides with the first. A fake cannot see
// the second module, and asserting the half it can see is still worth doing.
registerTeamProvider(provider) { once('registerTeamProvider'); record.teamProvider = provider },
registerEventTriggers(triggers) { once('registerEventTriggers'); record.triggers = triggers },
registerAudiences(audiences) { once('registerAudiences'); record.audiences = audiences },
registerEngagementSeeds(seeds) { once('registerEngagementSeeds'); record.engagementSeeds = seeds },
onBoot(fn) { once('onBoot'); record.hooks.onBoot = fn },
onShutdown(fn) { once('onShutdown'); record.hooks.onShutdown = fn },
}

View File

@@ -130,3 +130,163 @@ test('the manifest declares what the loader requires', () => {
// serves, so an entry in the module root would publish the whole module.
if (manifest.client) assert.ok(manifest.client.entry.includes('/'), 'client.entry must be in a subdirectory')
})
// ── The engagement seam ───────────────────────────────────────────────────
//
// Core validates most of what is declared here at registration, and a module
// that gets it wrong does not load. These tests are mostly NOT that validator
// restated: they are the rules a module can satisfy at boot and still have got
// WRONG in a way whose only symptom is mail somebody received. Where one does
// overlap core — the namespacing and subjectKey assertions below — it is because
// `npm test` is a cheaper place to meet the failure than a first boot, and the
// message here names the field.
test('every declared trigger is namespaced, ceilinged, and carries examples', () => {
const { api } = register()
const triggers = api.record.triggers
assert.ok(Array.isArray(triggers) && triggers.length, 'no triggers were declared')
for (const t of triggers) {
// Trigger ids and notification-stream ids are ONE namespace, so an id must
// carry this module's own prefix or it is a claim on somebody else's.
assert.ok(t.id.startsWith(`${manifest.id}.`), `${t.id} is not namespaced`)
// `ceiling` is required and has no default: there is no safe value to guess.
assert.ok(t.ceiling, `${t.id} declares no ceiling`)
// Core refuses this one too; failing it here just costs less. What the rule
// protects is the cooldown key — "once per world", not "once per user" — and
// a subjectKey naming nothing would key every subject on `undefined`.
const names = t.variables.map((v) => v.name)
assert.ok(names.includes(t.subjectKey), `${t.id}: subjectKey "${t.subjectKey}" is not a variable`)
for (const v of t.variables) {
// Not decoration: the example is what makes a template previewable and
// test-sendable without waiting for a real game event.
assert.ok('example' in v, `${t.id}.${v.name} has no example`)
// The type set is closed. A payload that needs a structure has outgrown
// interpolation, and a template cannot walk one.
assert.ok(
['string', 'int', 'float', 'boolean', 'datetime', 'url'].includes(v.type),
`${t.id}.${v.name} has type "${v.type}"`,
)
// A url is site-relative, because it ends up in an href in a mail somebody
// opens days later.
if (v.type === 'url') assert.match(v.example, /^\/[^/]/, `${t.id}.${v.name} must be site-relative`)
}
}
})
test('an audience resolves to nobody rather than to everybody when it fails', async () => {
const ctx = fakeCtx({ db: { query: () => Promise.reject(new Error('database is down')), pool: {} } })
const { api } = register(ctx)
const audience = api.record.audiences[0]
// The one behaviour worth a test of its own. Core treats a throw the same way,
// so this is not core's guard restated — it is the module choosing the same
// answer deliberately, and the reason is that the alternatives are both worse:
// "everyone" mails the wrong people and a stale answer mails yesterday's.
assert.deepStrictEqual(await audience.resolve({ clanId: 'clan-1' }), [])
})
test('a seeded rule names only this modules triggers, and its own or cores templates', () => {
const { api } = register()
const seeds = api.record.engagementSeeds
const ownKeys = new Set(seeds.templates.map((t) => t.key))
const coreKeys = new Set(['notify.event', 'inapp.event', 'notify.digest'])
for (const t of seeds.templates) {
// The key column is UNIQUE across the whole table, so an unprefixed
// `notify.event` from a module would collide with core's body and win.
assert.ok(t.key.startsWith(`${manifest.id}.`), `template ${t.key} is not namespaced`)
// `protected` means "the system breaks without this body" — true of a
// password reset and of nothing a module ships. Core refuses a module
// template that sets it, because it would take an operator's delete button
// away.
assert.ok(!('protected' in t), `template ${t.key} may not mark itself protected`)
}
for (const group of seeds.ruleGroups) {
for (const rule of group.rules) {
assert.ok(
api.record.triggers.some((t) => t.id === rule.trigger_id),
`${rule.name} names a trigger this module does not declare`,
)
for (const key of Object.values(rule.template_keys)) {
assert.ok(ownKeys.has(key) || coreKeys.has(key), `${rule.name} names an unknown template ${key}`)
}
// `enabled` is not a parameter, and a value passed for it is ignored
// rather than refused. Passing one anyway states an intention the platform
// will not honour, so the honest thing is not to write it.
assert.ok(!('enabled' in rule), `${rule.name} may not seed itself enabled`)
}
}
})
test('every seeded body is a shape the block registry will accept', () => {
const { api } = register()
// The gap this exists for: `registerEngagementSeeds` checks that `blocks` is a
// non-empty array and stops. The BODY is validated by core's block registry,
// which runs in the template editor and in the renderer — so a malformed block
// registers, seeds, and first shows itself when an operator opens the body or a
// rule fires. Core is not here to ask, so assert the two rules that are easy to
// get wrong and impossible to notice.
const HEADING_LEVELS = ['h1', 'h2', 'h3']
for (const t of api.record.engagementSeeds.templates) {
const ids = new Set()
for (const block of t.blocks) {
// Every block carries its own id, unique within the body: it is how the
// editor addresses one block, and how `inapp.event`'s renderer maps blocks
// onto the inbox row's columns by role.
assert.ok(block.id && typeof block.id === 'string', `${t.key}: a block has no id`)
assert.ok(!ids.has(block.id), `${t.key}: two blocks share the id "${block.id}"`)
ids.add(block.id)
assert.ok(block.type.startsWith('email.'), `${t.key}: ${block.type} is not an email block`)
// A heading's `level` is a SIZE token, not a number. `{ level: 2 }` reads
// perfectly and is refused, and it renders at the default size in any
// preview that skips validation — which is the whole trap.
if (block.type === 'email.heading') {
assert.ok(
HEADING_LEVELS.includes(block.props.level),
`${t.key}: heading level "${block.props.level}" must be one of ${HEADING_LEVELS.join(', ')}`,
)
}
}
}
})
test('the world event fires on the transition and not on the poll', async () => {
const boot = require('../boot')
// Online already, and reporting online again. The refresh writes, and nothing
// is announced: this runs every thirty seconds, and a rule on an event fired
// every thirty seconds mails somebody every thirty seconds. Core's cooldown
// would hold — but leaning on it means emitting "still up" and calling it news.
const steady = fakeCtx({ db: { query: () => Promise.resolve([{ online: 1 }]), pool: {} } })
require('../core')._reset()
require('../core').init(steady)
await boot.refresh()
assert.deepStrictEqual(steady.events.emit.calls, [])
// Offline before, online now. One emit, with the declared payload.
const flipped = fakeCtx({ db: { query: () => Promise.resolve([{ online: 0 }]), pool: {} } })
require('../core')._reset()
require('../core').init(flipped)
await boot.refresh()
assert.strictEqual(flipped.events.emit.calls.length, 1)
const [triggerId, envelope] = flipped.events.emit.calls[0]
assert.strictEqual(triggerId, 'examplegame.world.status_changed')
assert.strictEqual(envelope.data.status, 'online')
// A fresh install, where there is no previous row at all. Not a change — and
// announcing it would tell everyone the world came online the first time an
// operator started the site.
const fresh = fakeCtx({ db: { query: () => Promise.resolve([]), pool: {} } })
require('../core')._reset()
require('../core').init(fresh)
await boot.refresh()
assert.deepStrictEqual(fresh.events.emit.calls, [])
})