feat(engagement): let a module ship its own templates and rules (Phase 11b)

Phase 11a declared 24 triggers and stopped where the plan said it would. Standing
11b up found that the next sentence — "24 rules, all enabled = 0; bespoke template
bodies" — described work with no mechanism to land in: templateSeeds.js and
coreRules.js are core files with core arrays in them, and there was no
registerTemplates or registerRules anywhere in registries.js.

So a module could say what an event's payload was and could never say what the
mail should read like. That is tolerable for one trigger and not for a catalogue,
and it is decisive once the bodies carry domain prose core must not contain (§5.2).

Adds api.registerEngagementSeeds({ templates, ruleGroups }) — MODULE_API 1.9.0.
The module supplies data; core keeps seedOne's customized skip, its seed_version
comparison and the block registry's validation, which is the whole argument for a
registry over the ctx.query a module already holds: a copy of any of those living
outside engagement/ would drift the first time core improved the original, and the
drift would surface as a mail somebody already received.

The two halves behave differently, deliberately:

  - Templates re-ensure on every boot, so a bumped seedVersion reaches every
    deployment except the ones where an operator edited that row.
  - Rule groups are ONE-SHOT, each under its own settings guard — re-ensuring
    would resurrect a rule an operator deleted and reset one they enabled. This is
    11a's seed-key finding stated as an API rather than as a warning: a rule
    appended to an existing group reaches fresh installs only, and one that must
    reach stamped deployments takes a new group key.

Three prohibitions, each a shipped mistake that would only surface as mail: a
seeded rule is always enabled = 0 (Q3's invariant, ignored rather than refused so
a typo cannot take a module offline at boot); a module may not mark a template
protected; and a rule may only name its own trigger ids and its own or core's
template keys, with template keys namespaced because the key column is UNIQUE.

Runs from modules/lifecycle.js boot() rather than seedDefaults(), and that is
forced rather than chosen: server.js seeds before it requires app.js, and
requiring app.js is what runs the loader — at the moment core seeds, no module has
registered anything. Placed after the installed_modules reconcile (so a disabled
or failed module is skipped) and before the onBoot dispatch (so a module warming a
cache may assume its rules exist).

16 new tests; 1549 core tests green; check:modules clean.

Refs docs#/ENGAGEMENT.md Phase 11b decision 7.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 00:46:15 -05:00
parent 81e0338a69
commit cfd1cb3c3c
7 changed files with 788 additions and 2 deletions

View File

@@ -0,0 +1,179 @@
// ── Seeding what a module ships (ENGAGEMENT.md Phase 11b, decision 7) ──────
//
// Core's own bodies and rules are seeded from `seedDefaults()`, and a module's
// cannot be: `server.js` calls `seedDefaults()` BEFORE it requires `app.js`, and
// requiring `app.js` is what scans the volume and runs the loader. At the moment
// core seeds, no module has registered anything at all.
//
// So this runs from `modules/lifecycle.js` `boot()` instead — after the
// `installed_modules` reconcile, so a module the operator disabled or one that
// failed to load is skipped rather than seeded, and BEFORE the `onBoot`
// dispatch, so a module that warms a cache in `onBoot` may assume its rules
// exist.
//
// **It reuses core's two seeders rather than reimplementing them**, which is the
// whole argument for the registry existing (decision 7): `seedOne` owns the
// `customized` skip and the `seed_version` comparison, `validateEmailBlocks`
// owns what a renderable body is, and a module supplies data. A copy of either
// living outside this directory would drift the first time core improved the
// original — and the drift would surface as a mail somebody already received.
//
// ── The asymmetry, once more, because it is the thing to get right ─────────
//
// **Templates are re-ensured every boot.** A row carries `seed_key`,
// `seed_version` and `customized`, so re-ensuring is how a better default
// reaches a deployment without stealing an operator's edit (§4.6.1 property 3),
// and a template added in a later module version reaches every deployment rather
// than only fresh ones.
//
// **Rule groups are one-shot, each under its own settings guard.** Re-ensuring a
// rule would resurrect one an operator deleted and reset one they enabled. This
// is 11a's seed-key finding as a mechanism: a rule appended to an existing group
// reaches fresh installs only, and a rule that must reach already-stamped
// deployments takes a new group key. The module chooses; this file honours it.
//
// **Never throws.** It is on the boot path beside every other `safe()`-wrapped
// step in `lifecycle.boot()`, and a body that would not seed costs the shipped
// default — `renderByKey`'s fallback stays in charge — not the deployment.
const templatesDb = require('../model/engagement/engagementTemplates.db')
const rulesDb = require('../model/engagement/engagementRules.db')
const settingsDb = require('../model/settings/settings.db')
const emailBlocks = require('../emailBlocks')
const log = require('../utils/logger')('engagement')
/**
* The one-shot guard for one module's rule group.
*
* Namespaced by owner AND by group so two modules may use the same group name,
* and so a module can add a second group later without touching the first. Its
* VALUE is the timestamp — purely so an operator reading the settings table can
* tell when it ran; only its presence is read.
*/
const guardKey = (owner, group) => `engagement_module_rules_seeded:${owner}:${group}`
/**
* Ensure one module's templates, and bring un-customized rows up to the current
* seed. Idempotent.
*/
async function seedModuleTemplates(owner, templates, deps = {}) {
const templates_ = deps.templatesDb || templatesDb
const counts = { inserted: 0, updated: 0, skipped: 0, invalid: 0 }
for (const seed of templates) {
// Validated against the block registry before it is stored, exactly as core's
// own seeds are and for the same reason: a shipped block array no renderer
// understands sitting in the table reads to an operator as their deployment
// being broken. Refusing to write it leaves the fallback in charge and puts
// the reason in the boot log, with the module named.
const { valid, errors } = emailBlocks.validateEmailBlocks(seed.blocks)
if (!valid) {
log.error('a module template is invalid and was not seeded', { owner, key: seed.key, errors })
counts.invalid += 1
continue
}
try {
counts[await templates_.seedOne(seed)] += 1
} catch (err) {
log.error('module template seed failed', { owner, key: seed.key, message: err.message })
}
}
// The third arm of §4.6.1 property 3: a customized row is never touched, and
// the fact that a better default now exists is surfaced instead of applied.
let stale = []
try {
stale = await templates_.staleCustomized(
templates.map((t) => ({ key: t.key, seedVersion: t.seedVersion })),
)
} catch {
stale = []
}
if (stale.length) {
log.info('customized module templates have a newer shipped default', {
owner,
keys: stale.map((t) => t.key),
})
}
return { ...counts, stale: stale.map((t) => t.key) }
}
/**
* Seed one named rule group, once, under its own guard.
*
* Mirrors `coreRules.seedGroup` deliberately, including the stamp-on-partial
* behaviour: re-running would duplicate the rules that DID insert, and a
* duplicate rule is two mails per event — worse than the one missing rule an
* operator can add from the Rules screen.
*/
async function seedRuleGroup(owner, group, deps = {}) {
const rules_ = deps.rulesDb || rulesDb
const settings_ = deps.settingsDb || settingsDb
const summary = { inserted: 0, skipped: 0 }
const key = guardKey(owner, group.key)
try {
const seen = await settings_.get(key)
if (seen) return { ...summary, skipped: group.rules.length }
for (const rule of group.rules) {
try {
await rules_.insert(rule)
summary.inserted += 1
} catch (err) {
log.error('module rule seed failed', {
owner,
group: group.key,
trigger: rule.trigger_id,
message: err.message,
})
}
}
await settings_.set(key, new Date().toISOString())
if (summary.inserted) {
log.info('seeded module engagement rules, all disabled', {
owner,
group: group.key,
rules: summary.inserted,
note: group.note || undefined,
})
}
} catch (err) {
log.error('module rule group seeding failed', { owner, group: group.key, message: err.message })
}
return summary
}
/**
* Seed every registered module's engagement content.
*
* @param {object} [deps]
* @param {Function} [deps.seeds] () => [{ owner, templates, ruleGroups }]
* @param {Set} [deps.skip] owners not to seed (disabled or failed)
* @param {object} [deps.templatesDb] / [deps.rulesDb] / [deps.settingsDb] — test seams
*/
async function seedModuleEngagement({ seeds, skip = new Set(), ...dbs } = {}) {
// eslint-disable-next-line global-require
const read = seeds || require('../modules/registries').allEngagementSeeds
const totals = { templates: 0, rules: 0 }
for (const entry of read()) {
if (skip.has(entry.owner)) {
log.info('skipping engagement seeds for a module that is not booting', { owner: entry.owner })
continue
}
const t = await seedModuleTemplates(entry.owner, entry.templates || [], dbs)
totals.templates += t.inserted + t.updated
for (const group of entry.ruleGroups || []) {
const r = await seedRuleGroup(entry.owner, group, dbs)
totals.rules += r.inserted
}
log.info('module engagement seeds ensured', { owner: entry.owner, ...t })
}
return totals
}
module.exports = {
seedModuleEngagement,
seedModuleTemplates,
seedRuleGroup,
guardKey,
}