feat(events): schema, CRUD and the core action registry (Phase 1)
All checks were successful
PR Checks / client-build (pull_request) Successful in 26s
PR Checks / bot-tests (pull_request) Successful in 29s
PR Checks / server-tests (pull_request) Successful in 13m24s

EVENTS_PLAN.md Phase 1. Six of the nine core tables — the ones that do not
depend on the module contract — plus definitions CRUD, publish, archive, and
the action registry with core as its first registrant.

**Nothing dispatches.** There is no runner until Phase 2, so a run row is
created and stays `scheduled`. That is this phase's correct answer and the
surface renders it verbatim rather than hiding it.

Schema (`db/schema.sql`, append-only):
  event_series, event_definitions, event_versions, event_runs,
  event_run_steps, event_run_log. The four that need a writer —
  event_action_settings, event_run_budget, event_run_resources,
  event_run_participants — arrive with the phases that give them one.

Registry (`modules/registries.js` + `config/coreEventActions.js`):
  registerEventActions staging and commit, with its own id namespace, the
  closed risk and reversibility sets, revert() required iff and only iff
  reversible: 'ledger', a bounded budgetMs and a param shape whose every
  entry needs a type and an example. perform/revert/cost are stripped from
  everything the catalog serves. Core declares core.announce, core.wait and
  core.cue through the same staging area a module will use.

  It is reachable ONLY by registerCore(): loader.js builds its own api facade
  and has no method that delegates here, so no module can call it and
  MODULE_API_VERSION is untouched. Phase 7 adds the facade and the bump.

Surface (13 routes under /api/v1/admin/events):
  Reads staff-wide; publish, archive and run creation admin-only from this
  phase per EVENTS.md §N2, even though the switchboard they will consult does
  not exist yet — a button that is admin-only later and open now is a gate
  nobody notices was missing. The live run controls and `verify` are absent
  rather than stubbed, because nothing is in flight yet.

Four things the build settled, all recorded in docs:
  - event_definitions gained a `spec` column. A draft's working copy cannot
    be an event_versions row: that table is immutable and a run pins one.
  - The spec validator must accept its own output. It added `actionVersion`
    and `dormant` and then refused them as unknown keys, which would have made
    the second save of any definition — and publish's re-validation —
    impossible. A test caught it; both are now accepted and recomputed.
  - A param's `example` is required, optional params included, matching
    registerEventTriggers. It is the authoring form's placeholder.
  - Two routes the §API-surface table did not name: GET /admin/events/:id and
    GET /admin/events/series.

Core's three perform() bodies answer { ok: false, retry: false } rather than
{ ok: true }: `ok: true` on an action that did nothing is a recorded world
change that did not occur, which is the exact mistake §F's failure default
exists to prevent.

`conditions.checkLiteral` is exported and reused for step-param type checking
— one switch over the six types, so "is this a datetime" has one answer.

Verified: 44 new tests, whole server suite, `npm run check:modules`, routes
manifest and swagger regenerated (the manifest diff is +13 routes, zero moved).

Docs: RunicGateway/docs#209

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 23:29:07 -05:00
parent 6331b36c45
commit 8e03497eb3
23 changed files with 4714 additions and 1 deletions

View File

@@ -0,0 +1,134 @@
// ── event_definitions — SQL only ───────────────────────────────────────────
//
// EVENTS.md §D. The `.db.js` half of the pair: parameterised SQL and hydration,
// no policy. Everything that decides whether a write is allowed lives in
// `eventDefinitions.model.js`.
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) =>
row && {
...row,
spec: parseJson(row.spec, null),
}
// `current_version` is joined rather than stored: the list screen shows "v3" and
// the column that would hold it is a denormalisation of a row this query already
// has to reach for the publish date anyway.
const SELECT_LIST = `
SELECT d.*, s.name AS series_name, s.slug AS series_slug,
v.version AS current_version
FROM event_definitions d
LEFT JOIN event_series s ON s.id = d.series_id
LEFT JOIN event_versions v ON v.id = d.current_version_id
`
const list = async ({ state = null } = {}) => {
const rows = state
? await query(`${SELECT_LIST} WHERE d.state = ? ORDER BY d.updated_at DESC, d.id DESC`, [state])
: await query(`${SELECT_LIST} ORDER BY d.updated_at DESC, d.id DESC`)
return rows.map(hydrate)
}
const getById = async (id) => {
const [row] = await query(`${SELECT_LIST} WHERE d.id = ?`, [id])
return hydrate(row)
}
const getBySlug = async (slug) => {
const [row] = await query(`${SELECT_LIST} WHERE d.slug = ?`, [slug])
return hydrate(row)
}
/** Does any OTHER definition hold this slug? The uniqueness pre-check. */
const slugTaken = async (slug, exceptId = null) => {
const rows = exceptId
? await query('SELECT id FROM event_definitions WHERE slug = ? AND id <> ?', [slug, exceptId])
: await query('SELECT id FROM event_definitions WHERE slug = ?', [slug])
return rows.length > 0
}
const insert = async (d) => {
const result = await query(
`INSERT INTO event_definitions
(title, slug, summary, body, image_url, owner_module, series_id, series_order,
concurrency_key, grace_seconds, timezone, spec, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
d.title,
d.slug,
d.summary,
d.body,
d.image_url,
d.owner_module,
d.series_id,
d.series_order,
d.concurrency_key,
d.grace_seconds,
d.timezone,
JSON.stringify(d.spec),
d.created_by,
d.created_by,
],
)
return result.insertId
}
const update = (id, d) =>
query(
`UPDATE event_definitions
SET title = ?, slug = ?, summary = ?, body = ?, image_url = ?, series_id = ?,
series_order = ?, concurrency_key = ?, grace_seconds = ?, timezone = ?,
spec = ?, updated_by = ?
WHERE id = ?`,
[
d.title,
d.slug,
d.summary,
d.body,
d.image_url,
d.series_id,
d.series_order,
d.concurrency_key,
d.grace_seconds,
d.timezone,
JSON.stringify(d.spec),
d.updated_by,
id,
],
)
/**
* Point a definition at the version it just published, and mark it `ready`.
*
* One statement, because the two halves are the same fact: `ready` means "a
* version has been published and the schedule is live" (§E), so a state without
* a `current_version_id` is a lie the scheduler would act on.
*/
const markReady = (id, versionId, userId) =>
query(
`UPDATE event_definitions
SET state = 'ready', current_version_id = ?, updated_by = ?
WHERE id = ?`,
[versionId, userId, id],
)
/**
* Archive. Never a hard delete while runs reference it (§ API surface) — and the
* schema would refuse one anyway, because `event_runs.version_id` RESTRICTs.
* Archiving is what "delete" means on this screen, and the row keeps its history.
*/
const archive = (id, userId) =>
query("UPDATE event_definitions SET state = 'archived', updated_by = ? WHERE id = ?", [userId, id])
module.exports = {
list,
getById,
getBySlug,
slugTaken,
insert,
update,
markReady,
archive,
}