27 Commits

Author SHA1 Message Date
0f29f0acb2 Merge pull request 'feat(events): a trigger can start a run (Rust §14.3 stage 9, D370)' (#216) from feat/event-trigger-starts into main
All checks were successful
sync-project-tree / sync (push) Successful in 21s
Build container images / build (push) Successful in 1m31s
SonarQube / analysis (push) Successful in 9m14s
Build container images / deploy (push) Successful in 56s
Reviewed-on: #216
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-16 07:07:59 +00:00
c9e992588b feat(events): a trigger can start a run
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 35s
PR Checks / client-build (pull_request) Successful in 44s
PR Checks / server-tests (pull_request) Successful in 12m45s
Rust PLAN_REDESIGNS §14.3.12 (D370), stage 9 of §14.3. A definition's
published version may carry `starts`: a trigger, a condition and a
cooldown. A matching firing creates a run of it, now.

- spec: `starts` validated by the phase gate's own function (same
  grammar, same dormant rule; a dormant start refuses publish), a
  cooldown from 0m to 7d (30m default), at most ten, event.* refused.
- events/starts.js: the emit path's third subscriber, beside dispatch
  and the gate observer. An unverified version starts nothing; one run
  at a time per definition and the cooldown are one conditional UPDATE
  on the new event_trigger_starts table; the occurrence key makes one
  firing reported twice one run. Ignored firings are counted by why.
- event_runs.origin: the firing (trigger, label, time, subject, matched
  condition, declared variables), also on the run.created audit line.
- Editor: a "Started by the game" panel using the gate's condition
  builder, with the ignored-firings line. Run console: "Started because
  ... fired".
- No module contract change and no MODULE_API bump.

Tests: eventStarts (server 21, client 8); eventRunnerSql +7 against a
real MariaDB (75/75); Module-uo proof on uo.champ.boss_up against the
dev database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-16 01:51:55 -05:00
eb773693d3 Merge pull request 'feat(events): a failed step may say when to retry (MODULE_API 1.15.0)' (#215) from feat/event-step-retry-after into main
Some checks failed
sync-project-tree / sync (push) Successful in 12s
Build container images / build (push) Successful in 1m38s
SonarQube / analysis (push) Successful in 9m29s
Build container images / deploy (push) Has been cancelled
Reviewed-on: #215
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-15 07:47:46 +00:00
769794d183 feat(events): a failed step may say when to retry (MODULE_API 1.15.0)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 48s
PR Checks / client-build (pull_request) Successful in 59s
PR Checks / server-tests (pull_request) Successful in 6m6s
A module's perform() may answer { ok: false, retry: true, retryAfterMs }
and the runner waits that long instead of the flat EVENT_STEP_RETRY_MS
(Rust PLAN_REDESIGNS §14.3.13, D371). Dangerous Treasures' warm-up is the
first user.

- dispatch.classify reads it on the retry shape only, clamped to 60 000 to
  1 800 000 ms; a value that is not a number is dropped and logged, and the
  step retries on the flat delay.
- It is one attempt of EVENT_STEP_MAX_ATTEMPTS and degrades the run like any
  retry. A run paused or cancelled in the wait is not picked up.
- Every step.retry log line now carries retryAt (and retryAfterMs when
  hinted); the run console reads "retrying at 20:10".
- MODULE_API 1.15.0, additions only; the engagement manifest is regenerated.
  Module-uo (^1.10.0) answers none of it and is unaffected.
- Test harness: resourcesDb.finishedRunsWithNothingLeft was never stubbed in
  eventRunner.test.js, so a tick that reached the cleanup sweep with a
  terminal run waited on the dead pool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-15 02:39:43 -05:00
a981b2b854 Merge pull request 'feat(events): a param that holds several values (MODULE_API 1.14.0)' (#213) from feat/event-param-multiple into main
Some checks failed
sync-project-tree / sync (push) Successful in 29s
Build container images / build (push) Successful in -18s
SonarQube / analysis (push) Successful in 17m58s
Build container images / deploy (push) Has been cancelled
Reviewed-on: #213
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-13 01:03:19 +00:00
743f1bc8b2 feat(events): a param that holds several values (MODULE_API 1.14.0)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 47s
PR Checks / client-build (pull_request) Successful in 48s
PR Checks / server-tests (pull_request) Successful in 13m55s
Rust PLAN_REDESIGNS §12.3 (D344): an event action param may declare
`multiple: true`, with an optional `max` (1-100, 20 when left out), on a
`string` or `int` param. The permission reward steps take several permissions
in one step through it.

- registries: the flag and `max` are checked at registration and served in the
  catalog; refused on other types, on a duration, on a template's inputs, and
  with a list as the example. A param that does not say it reads back exactly
  as declared, without the keys.
- spec: the value is a JSON array, each item the type's literal, duplicates
  dropped in order, at most `max`; a bare value is a list of one; `required`
  means at least one; an empty item is refused.
- authorize: a multiple param's example is priced as a list of one, since
  cost() is handed the array.
- editor: a multi-select. Chips above a grouped, filterable checklist for a
  source that answered; the typeahead for a searchable source; a tag box
  otherwise. Ticking past max is refused in words. A new step holds the
  example as a list of one.
- run console: params read as `name: value`, a list joined by commas.
- MODULE_API 1.13.0 -> 1.14.0 on both halves; engagement-triggers.json and the
  catalog's OpenAPI note regenerated.

Additive only: Module-uo (`^1.10.0`) declares no multiple param.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-12 15:40:30 -05:00
ca7ec53b14 Merge pull request 'feat(events): the step editor reworked, and event templates (MODULE_API 1.13.0)' (#212) from feat/event-step-editor into main
Some checks failed
sync-project-tree / sync (push) Successful in 21s
Build container images / build (push) Successful in 1m50s
SonarQube / analysis (push) Successful in 17m50s
Build container images / deploy (push) Has been cancelled
Reviewed-on: #212
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-12 09:53:42 +00:00
e58857c133 feat(events): a searchable source's chosen note is found when the page lacks it
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 1m47s
PR Checks / client-build (pull_request) Successful in 1m58s
PR Checks / server-tests (pull_request) Successful in 14m58s
A searchable source answers the editor a bounded first page, so the value an
author picked (or a template filled in) may not be on it, and its note with it.
useChosenNote asks the source for that value as a search term, once per value,
and shows the exact match's note. Found building the Rust kit warning
(PLAN_REDESIGNS §2.6), whose source - rust.options.grouppermissions - is
searchable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-12 02:23:18 -05:00
3e243ce772 feat(events): the step editor reworked, and event templates (MODULE_API 1.13.0)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 2m26s
PR Checks / client-build (pull_request) Successful in 2m44s
PR Checks / server-tests (pull_request) Successful in 20m38s
Rust PLAN_REDESIGNS §2 (U-3-U-6, F11; D192, D334), core half. Game-agnostic:
Module-uo's steps get the new controls and nothing else.

Contract (MODULE_API 1.12.0 -> 1.13.0, four optional additions):
- api.registerEventTemplates([{ id, label, description, inputs, build }]):
  inputs are params (<= 8); core checks them, calls build() (10 s), validates
  the result as a spec and answers an unsaved draft.
  POST /admin/events/catalog/templates/:templateId (admin, editor).
- a param's duration: 'minutes' (int/float only); core.lease's minutes has it.
- a lease's example for its value.
- an option row's note (<= 300 chars), shown under the chosen field.

Editor:
- no type tags or bare asterisks; a required field says so in words once a
  save has been tried with it empty (and the save stops before the round trip).
- boolean: toggle when required, [Not set] [Yes] [No] when optional (D334).
- a choice of two or three is a row of buttons (lease values, small sources).
- core.lease drawn as the chosen lease: picked by label; value by the lease's
  type, range, values and example; target picker over target.source (F11);
  minutes with the lease's longest hold.
- a timed step keeps its run open: a phase with no advance rule gets
  after: <longest hold> when a timed step is added; a sentence under any phase
  whose run can end sooner (U-6).
- Start asks "Publish and start" or "Start version N" when the working copy is
  ahead of the published version (draftAhead on GET/PUT/publish; U-5).
- New event can start from a module's template.
- core's own examples name no game (§0.9).

Swagger, routes.manifest/guards and engagement-triggers.json regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-12 02:08:04 -05:00
43f706c003 Merge pull request 'fix(events): the public phase label finds the phase by key (runicnpc D314)' (#211) from fix/event-public-phase-label into main
Some checks failed
sync-project-tree / sync (push) Successful in 18s
Build container images / build (push) Successful in 1m39s
SonarQube / analysis (push) Successful in 17m24s
Build container images / deploy (push) Has been cancelled
Reviewed-on: #211
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-07 02:50:14 +00:00
ef93c73d2c fix(events): the public phase label finds the phase by key (runicnpc D314)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 36s
PR Checks / client-build (pull_request) Successful in 7m50s
PR Checks / server-tests (pull_request) Successful in 13m50s
eventPublic.phaseLabel matched a run's current_phase against p.id, but spec.js
validates and the engine writes the phase's `key`, so every live run's public
page read "Under way" since Events Phase 14a, UO's events included. It now
matches `key` first and still accepts `id` second. The test fixture moves to
`key`, as real specs are, and a unit test covers a UO-shaped spec, the id
fallback, key-before-id and an unknown phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-06 16:57:46 -05:00
0a37a44164 Merge pull request 'feat(events): an event action's progress() on a live run's public page (MODULE_API 1.12.0)' (#210) from feat/events-action-progress into main
Some checks failed
sync-project-tree / sync (push) Successful in 26s
Build container images / build (push) Successful in 1m46s
SonarQube / analysis (push) Failing after 16m44s
Build container images / deploy (push) Has been cancelled
Reviewed-on: #210
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-10-06 12:58:52 +00:00
9ddb59a326 feat(events): an event action's progress() on a live run's public page (MODULE_API 1.12.0)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 38s
PR Checks / client-build (pull_request) Successful in 49s
PR Checks / server-tests (pull_request) Successful in 20m42s
An event action may declare an optional `progress(envelope)`: how its
step stands while the run is live. Core accepts two shapes and
interprets neither:

- a count: { label, left, of }, rendered "Bandits: 3 of 8 left";
- a percentage: { label, percent }, rendered "The Juggernaut: 62%".

How core asks:

- `events/progress.js` asks each step of a live run whose action has
  one. It passes the step's own held ledger rows and the reader's
  account id, so the module applies its own visibility.
- Each call has a 2 s deadline. A throw, a late answer or any other
  shape is a line not shown, never an error on the page.
- One answer per run and reader is cached for 5 s.
- The public event's live occurrence carries the lines as `progress`.
  The route takes an optional session for the reader.
- The page renders them under the phase label and re-reads them every
  15 s while the event is live.

Core stays game-agnostic: no game's words are in it. Additive, so a
minor bump. Module-uo declares ^1.10.0, registers no action with
progress(), and its actions and pages are unchanged.

From RunicNPC stage 8 (D304, D305).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-06 02:47:00 -05:00
f0e7d2aa2a Merge pull request 'feat(events): an expired ledger status and ctx.events.expired (MODULE_API 1.11.0)' (#209) from feat/events-expired-status into main
All checks were successful
sync-project-tree / sync (push) Successful in 17s
Build container images / build (push) Successful in -1s
Build container images / deploy (push) Successful in 39s
SonarQube / analysis (push) Successful in 17m21s
Reviewed-on: #209
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-27 06:10:43 +00:00
224e2b4dbc fix(events): settle a finished run whose last resource expired while it ran
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 31s
PR Checks / client-build (pull_request) Successful in 31s
PR Checks / server-tests (pull_request) Successful in 20m48s
Found walking Rust PLAN_FIXES step 2 (run 46 on the walk core): a zone expired
while its run was still going, so expireResource left the run's cleanup status
to its terminal path. When the run was cancelled the sweep never selected it,
because runsNeedingCleanup joins on an unresolved row and it had none, so
cleanup_status sat at `pending` for ever over an empty ledger.

The sweep now settles finished runs that are `pending` with no unresolved row
as `complete` (never over `incomplete`, which is a human's to clear). Checked
against the walk database: the query returns run 46 and nothing else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 22:19:17 -05:00
cc1f49af29 feat(events): an expired ledger status and ctx.events.expired (MODULE_API 1.11.0)
All checks were successful
PR Checks / client-build (pull_request) Successful in 35s
PR Checks / server-tests (pull_request) Successful in 5m48s
PR Checks / bot-tests (pull_request) Successful in 7m51s
A game that ends a resource at its own deadline — a Rust zone erased when its
time is up — could reach core only through ctx.events.reconcile(), which files
it `orphaned`: amber, "it vanished", and still claimable for a revert. The new
call files it as the plan working (Rust PLAN_FIXES F14, D170, D183):

- event_run_resources.status gains `expired`, terminal like `reverted`: the
  sweep never takes it back, live_marker releases the target, and it joins
  neither HELD nor UNRESOLVED. The ENUM ALTER re-runs as a no-op on every boot
  (checked on MariaDB 11.8 with the stored generated column depending on it).
- ctx.events.expired({ kind, ref }) marks the calling module's own pending,
  confirmed or orphaned rows for that target expired and logs
  `resource.expired`; a revert in flight is left to finish. The owner is bound
  by the loader, like reconcile. A finished run whose last unresolved row this
  was goes to cleanup `complete`, even from `incomplete`.
- The run console shows it green, "ended by the game on time".

Additions only, so minor. Module-uo (coreApi ^1.10.0) calls none of it and
reads no ledger status; the contract test now asserts the range still holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 21:13:07 -05:00
1a76b98d76 Merge pull request 'fix(modules): a site runs one module; the installer refuses a second' (#204) from fix/one-module-per-site into main
All checks were successful
sync-project-tree / sync (push) Successful in 10s
Build container images / build (push) Successful in -2s
Build container images / deploy (push) Successful in 1m46s
SonarQube / analysis (push) Successful in 9m11s
Reviewed-on: #204
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-26 22:28:57 +00:00
a169a463a5 Merge branch 'main' into fix/one-module-per-site
All checks were successful
PR Checks / client-build (pull_request) Successful in 33s
PR Checks / bot-tests (pull_request) Successful in 32s
PR Checks / server-tests (pull_request) Successful in 5m47s
2026-09-26 22:22:56 +00:00
90ba8cca16 Merge pull request 'feat(events): publish runId on a public calendar run entry (Rust D125)' (#208) from feat/public-calendar-run-id into main
Some checks failed
sync-project-tree / sync (push) Successful in 12s
Build container images / build (push) Successful in 1m50s
Build container images / deploy (push) Successful in 42s
SonarQube / analysis (push) Failing after 6m11s
Reviewed-on: #208
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-25 17:43:50 +00:00
b5616f359c feat(events): publish runId on a public calendar run entry (Rust D125)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 39s
PR Checks / client-build (pull_request) Successful in 42s
PR Checks / server-tests (pull_request) Successful in 5m54s
A run entry on GET /public/events now names its run, the same id the
event page already publishes on each occurrence and `?run=` takes. A
Rust map marker carries core's run id and nothing else about its event,
so without this the app could only find the event by fetching every
event page.

A projected entry has no runId: nothing is committed to it. Rehearsals
and unlisted events stay absent from the calendar, so their markers
stay unlinked. The web calendar ignores the field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 07:38:59 -05:00
e4f088e90b fix(modules): a site runs one module; the installer refuses a second
All checks were successful
PR Checks / client-build (pull_request) Successful in 33s
PR Checks / bot-tests (pull_request) Successful in 34s
PR Checks / server-tests (pull_request) Successful in 13m28s
A site is one game, and the module contract already has singletons that
assume it. registerTeamProvider holds one value per deployment, and a
second module registering one fails that module's whole load. The loader
scans alphabetically, so installing module-rust (which gains a Team
provider in its phase 9) beside module-uo would have taken uo down, not
rust.

install() now refuses, with 409 and before the artifact is downloaded,
any install whose id differs from a module already on the volume. An
upgrade of the installed module is still accepted; to change game,
remove the module first. Both install surfaces share this path, so a
MODULES declaration naming two modules installs the first and reports
the second as refused without failing the boot.

"Installed" means what the loader would scan: a directory named with a
module id that holds a module.json. An install's scratch directory and a
swap's aside copy do not count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 01:26:52 -05:00
702ab89ae2 Merge pull request 'fix(admin): stop a long action name printing over the activity row beside it' (#203) from fix/activity-action-overflow into main
All checks were successful
sync-project-tree / sync (push) Successful in 13s
Build container images / build (push) Successful in 1m29s
Build container images / deploy (push) Successful in 46s
SonarQube / analysis (push) Successful in 9m11s
Reviewed-on: #203
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-21 22:24:29 +00:00
9e1f591b25 fix(admin): stop a long action name printing over the activity row beside it
All checks were successful
PR Checks / client-build (pull_request) Successful in 57s
PR Checks / server-tests (pull_request) Successful in 6m9s
PR Checks / bot-tests (pull_request) Successful in 8m3s
The dashboard renders an activity row action in a fixed `width: 110` span with
`flex: none` and no overflow handling, so a name wider than that overflows its
box and prints on top of the detail text next to it.

Core own actions all fit. A module one need not: `module-rust` writes
`rust.account.unlink.staff` when staff sever a player Steam link, and it
overlapped `steamId: …` on a live dashboard. `module-uo` `uoLink.account.link`
is already close to the edge.

`minWidth` instead of `width` keeps the column aligned for every short name and
lets a longer one push the detail right rather than sit under it. One property,
verified in a browser with both rows on screen.

Found while walking module-rust phase 6; raised here rather than worked around
there, because a module may legitimately name an action and shortening one
module names only moves the ceiling to the next one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 09:10:43 -05:00
efa9db7330 Merge pull request 'chore(tools): delete the cliloc converter the Asset Bridge replaced (Asset Bridge cutover, 2 of 5)' (#202) from edge into main
All checks were successful
sync-project-tree / sync (push) Successful in 34s
Build container images / build (push) Successful in 22s
Build container images / deploy (push) Successful in 38s
SonarQube / analysis (push) Successful in 9m11s
Reviewed-on: #202
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-15 10:20:24 +00:00
720103e3d4 Merge branch 'main' into edge
All checks were successful
PR Checks / client-build (pull_request) Successful in 30s
PR Checks / bot-tests (pull_request) Successful in 31s
PR Checks / server-tests (pull_request) Successful in 13m24s
2026-09-15 10:04:54 +00:00
f373f2e897 Merge pull request 'chore(tools): delete the cliloc converter the Asset Bridge replaced (Phase 2)' (#201) from feat/asset-bridge-p2 into edge
All checks were successful
PR Checks / client-build (pull_request) Successful in 40s
PR Checks / bot-tests (pull_request) Successful in 41s
PR Checks / server-tests (pull_request) Successful in 13m28s
Reviewed-on: #201
2026-09-10 16:20:24 +00:00
655fbf3f69 Merge pull request 'feat(events): the Event System — core (Phase 16b cutover, 2 of 6)' (#199) from edge into main
Some checks failed
sync-project-tree / sync (push) Successful in 1m32s
Build container images / build (push) Successful in 2m12s
Build container images / deploy (push) Successful in 49s
SonarQube / analysis (push) Failing after 33m0s
Reviewed-on: #199
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-09-10 00:43:29 +00:00
59 changed files with 5026 additions and 139 deletions

View File

@@ -518,6 +518,10 @@ export const api = {
const qs = q ? `?${new URLSearchParams({ q }).toString()}` : ''
return req(`/admin/events/catalog/options/${encodeURIComponent(sourceId)}${qs}`)
},
// MODULE_API 1.13.0. Fill an event template in; the answer is a draft the
// editor opens, and nothing is saved until the author saves it.
buildEventTemplate: (templateId, inputs) =>
req(`/admin/events/catalog/templates/${encodeURIComponent(templateId)}`, { method: 'POST', body: { inputs } }),
// Phase 6. The dry run is admin+editor: it dispatches nothing, and the author
// who wrote the definition is who should be able to price it against the caps
// before asking an admin to publish it. A report with findings comes back 200

View File

@@ -133,7 +133,9 @@ const nextPhaseKey = (phases) => {
export function blankStep(action) {
const params = {}
for (const p of action?.params || []) {
if (p.required || p.example !== undefined) params[p.name] = p.example
// A list's example is one value (MODULE_API 1.14.0), so the step starts
// holding that one.
if (p.required || p.example !== undefined) params[p.name] = p.multiple ? [p.example] : p.example
}
return {
actionId: action?.id || '',
@@ -219,6 +221,89 @@ export function whereFormFrom(where) {
}
}
// ── Starting from a trigger (Rust PLAN_REDESIGNS §14.3.12, D370) ───────────
//
// A start is a phase gate's trigger and condition plus a cooldown, so the form
// holds it in the gate's own fields — and the same `WhereBuilder` draws it. The
// server (`events/spec.js`) decides; this only carries the fields.
export const DEFAULT_COOLDOWN = '30m'
// Core's own lifecycle triggers cannot start a run; the editor does not offer
// them, and the server refuses them if posted anyway.
export const isStartableTrigger = (trigger) => !String(trigger?.id || '').startsWith('event.')
export function blankStart() {
return { on: '', cooldown: DEFAULT_COOLDOWN, dormant: false, ...blankWhere() }
}
/** The stored `starts`, as the form's rows. */
export function startsFormFrom(starts) {
return (starts || []).map((s) => ({
...blankStart(),
on: s.on || '',
cooldown: s.cooldown ?? DEFAULT_COOLDOWN,
dormant: Boolean(s.dormant),
...whereFormFrom(s.where),
}))
}
/**
* The form's starts as the spec's list. A row with no trigger chosen is dropped
* rather than posted — it is a half-added row, not a start the author wrote.
*/
export function startsPayload(rows, errors, triggersById = new Map()) {
const out = []
;(rows || []).forEach((row, i) => {
if (!row.on) return
const gate = advancePayload(
{ ...row, kind: 'on' },
`Start ${i + 1}`,
errors,
triggersById.get(row.on)?.variables || [],
)
const entry = { on: row.on, cooldown: String(row.cooldown ?? '').trim() || DEFAULT_COOLDOWN }
if (gate?.where) entry.where = gate.where
out.push(entry)
})
return out
}
/**
* Why a run exists, when a game firing started it — the console's sentence.
* Null for a run started by hand or by the schedule.
*/
export function describeOrigin(origin) {
if (!origin || origin.kind !== 'trigger') return null
const vars = Object.entries(origin.variables || {})
.filter(([k]) => k !== '_truncated')
.map(([k, v]) => `${k} ${typeof v === 'string' ? v : JSON.stringify(v)}`)
const label = origin.label || origin.triggerId
return [
`Started because “${label}” fired`,
origin.matched ? ` (matching ${origin.matched})` : '',
vars.length ? `: ${vars.join(' · ')}` : '',
].join('')
}
/**
* The editor's line about what its trigger starts have done — or null when a
* trigger has never tried. "2 firings ignored while running, 1 in its cooldown".
*/
export function describeTriggerStarts(state) {
if (!state) return null
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
const ignored = [
state.ignoredRunning ? `${plural(state.ignoredRunning, 'firing')} ignored while a run was going` : null,
state.ignoredCooldown ? `${plural(state.ignoredCooldown, 'firing')} ignored in the cooldown` : null,
state.ignoredUnverified
? `${plural(state.ignoredUnverified, 'firing')} ignored because the published version is not verified`
: null,
].filter(Boolean)
const last = state.lastRunId ? `Last started run #${state.lastRunId}` : 'No run started by a trigger yet'
return ignored.length ? `${last}; since then ${ignored.join(', ')}.` : `${last}.`
}
/** The editor's working state, from what `GET /admin/events/:id` returned. */
export function formFromDefinition(event) {
const spec = event?.spec || {}
@@ -241,6 +326,7 @@ export function formFromDefinition(event) {
// `false`, and `||` would quietly re-list it on the next save.
listed: event?.listed ?? true,
...scheduleFormFrom(spec.schedule),
starts: startsFormFrom(spec.starts),
phases: (spec.phases || []).map((p) => ({
key: p.key || '',
label: p.label || '',
@@ -345,6 +431,8 @@ export function payloadFromForm(form, { triggersById = new Map() } = {}) {
}
})
const starts = startsPayload(form.starts, errors, triggersById)
if (errors.length) return { ok: false, errors }
return {
@@ -361,7 +449,10 @@ export function payloadFromForm(form, { triggersById = new Map() } = {}) {
timezone: form.timezone,
listed: Boolean(form.listed),
listed: Boolean(form.listed),
spec: { schedule: scheduleFromForm(form), phases },
// `starts` only when there is one, as the server stores it (D370).
spec: starts.length
? { schedule: scheduleFromForm(form), starts, phases }
: { schedule: scheduleFromForm(form), phases },
},
}
}
@@ -545,7 +636,9 @@ export const PARAM_JSON = 'json'
* is what the author needs to see — and a form that dropped it would post a
* step that saves cleanly having deleted something they typed.
* • **a value no single control can hold** — an object or an array against a
* scalar declaration.
* scalar declaration, or anything but a flat list against a `multiple` one
* (MODULE_API 1.14.0). A bare value there is a list of one, as the server
* reads it, and the multi-select shows it as one chip.
*/
export function paramsRenderable(action, params) {
if (!action) return { ok: false, reason: 'the module that registered this action is not installed' }
@@ -554,6 +647,13 @@ export function paramsRenderable(action, params) {
if (!declared.has(name)) {
return { ok: false, reason: `this step carries "${name}", which ${action.id} does not declare` }
}
if (declared.get(name).multiple) {
const items = Array.isArray(value) ? value : [value]
if (items.some((v) => v !== null && typeof v === 'object')) {
return { ok: false, reason: `"${name}" holds a structure, which a list of values cannot hold` }
}
continue
}
if (value !== null && typeof value === 'object') {
return { ok: false, reason: `"${name}" holds a ${Array.isArray(value) ? 'list' : 'structure'}, which no single field can hold` }
}
@@ -625,6 +725,227 @@ export function setParam(step, name, raw, type) {
*/
export const datetimeInputValue = (value) => (typeof value === 'string' ? value.slice(0, 16) : '')
// ── A param that holds several values (MODULE_API 1.14.0, Rust PLAN_REDESIGNS §12.3) ──
/**
* A `multiple` param's value as the list the multi-select draws: an array as
* stored, a bare value as a list of one (the server's own reading), and nothing
* as the empty list.
*/
export function listValue(value) {
if (value === undefined || value === null || value === '') return []
return Array.isArray(value) ? value : [value]
}
/**
* Write a `multiple` param's whole list, and give back the whole box.
*
* Each item is coerced as `setParam` coerces one value, duplicates dropped
* keeping the first, and **an empty list removes the key** — `setParam`'s rule,
* for its reason: the server reads absent and `[]` alike, and "is required" is
* the error a required list left empty should get.
*/
export function setParamList(step, name, items, type) {
const parsed = parseParams(step?.paramsText)
if (parsed.error) return step?.paramsText || '{}'
const next = { ...parsed.params }
const out = []
for (const raw of items || []) {
if (raw === '' || raw === undefined || raw === null) continue
const value = coerceLiteral(type, raw)
if (!out.some((v) => v === value)) out.push(value)
}
if (out.length) next[name] = out
else delete next[name]
return JSON.stringify(next, null, 2)
}
/**
* Add one value to a list, or say why not. `{ list }` or `{ refused }`, so the
* control can put the sentence where the click was rather than silently doing
* nothing past `max`.
*/
export function addToList(list, value, max) {
const text = String(value ?? '').trim()
if (!text) return { list }
if (list.some((v) => String(v) === text)) return { list }
if (max && list.length >= max) return { refused: `This takes at most ${max} — remove one first.` }
return { list: [...list, text] }
}
/**
* The options a filter box leaves, matched on value, label and group alike,
* case-insensitively. The order is the source's own — a source sorts its rows
* (§12.2) and the editor keeps it.
*/
export function filterOptions(options, term) {
const t = String(term || '').trim().toLowerCase()
if (!t) return options || []
return (options || []).filter((o) =>
[o.value, o.label, o.group].some((s) => String(s || '').toLowerCase().includes(t)))
}
/**
* One step's params as a line the run console can show: `name: value`, a list
* joined by commas, anything else as its JSON. Shown rather than the raw object
* so a list of ten permissions reads as ten names, not as brackets and quotes.
*/
export function describeParams(params) {
if (!params || typeof params !== 'object') return ''
return Object.entries(params)
.map(([k, v]) => {
if (Array.isArray(v) && v.every((x) => x === null || typeof x !== 'object')) return `${k}: ${v.join(', ')}`
return `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`
})
.join(' · ')
}
// ── The step editor's own rules (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2) ──
//
// What the controls need to decide and nothing the server re-decides: which
// control a field gets, which required fields are empty, and whether a phase
// gives a timed step back before its time is up. The server still refuses a
// missing param by name — these exist so the form can say it first, in place.
/**
* A boolean as the control holds it. A lease's value is a string param that the
* lease reads as a boolean, so "true" and "false" are booleans here too.
*/
export function boolValue(value) {
if (value === true || value === 'true') return true
if (value === false || value === 'false') return false
return null
}
/**
* Should this source be drawn as a row of buttons? (§2.4)
*
* Two or three choices that fit on one line, from a source that answered and is
* not searched. A dropdown of two hides the other choice behind a click.
*/
export function isSegmentable(entry) {
return Boolean(
entry && entry.state === 'ok' && !entry.searchable &&
entry.options.length >= 2 && entry.options.length <= 3,
)
}
/** The note on the chosen option, if it carries one (§2.6). */
export function noteFor(entry, value) {
if (!entry || entry.state !== 'ok' || value === undefined || value === null || value === '') return null
const chosen = entry.options.find((o) => o.value === String(value))
return chosen?.note || null
}
/**
* The required params a step leaves empty, by name. `core.lease`'s `target` is
* optional on the action and required by a targeted LEASE, so the lease is
* asked too when there is one.
*/
export function missingParams(step, action, leasesById = new Map()) {
if (!action) return []
const parsed = parseParams(step?.paramsText)
if (parsed.error) return []
const empty = (v) => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)
const missing = (action.params || []).filter((p) => p.required && empty(parsed.params[p.name])).map((p) => p.name)
if (action.id === 'core.lease') {
const lease = leasesById.get(parsed.params.lease)
if (lease?.target && empty(parsed.params.target)) missing.push('target')
}
return missing
}
/** `30m`, `2h`, `90s`, `1d` → minutes. Null for anything the server would refuse. */
export function afterMinutes(after) {
const m = /^(\d{1,6})(s|m|h|d)$/.exec(String(after ?? '').trim())
if (!m) return null
const n = Number(m[1])
return { s: n / 60, m: n, h: n * 60, d: n * 1440 }[m[2]]
}
/** The longest declared duration in a step, in minutes; 0 for an untimed one. */
export function stepMinutes(step, action) {
const parsed = parseParams(step?.paramsText)
if (parsed.error || !action) return 0
let longest = 0
for (const p of action.params || []) {
if (p.duration !== 'minutes') continue
const n = Number(parsed.params[p.name])
if (Number.isFinite(n) && n > longest) longest = n
}
return longest
}
/** The longest timed step in a phase, in minutes. */
export const phaseMinutes = (phase, actionById) =>
Math.max(0, ...(phase?.steps || []).map((s) => stepMinutes(s, actionById.get(s.actionId))))
/**
* How long, at the least, the run goes on from the start of phase `pi`, in
* minutes — or Infinity when a phase from there on waits for something in the
* game, which may take any time at all.
*
* **Why the RUN and not the phase.** Teardown gives everything back when the run
* ends, so a 10-minute hold in phase 1 of three is safe if phases 2 and 3 take
* ten minutes between them. A phase with no advance rule ends when its steps do,
* which is counted as no time: a floor, never a promise.
*/
export function runFloorMinutes(phases, pi) {
let total = 0
for (const phase of (phases || []).slice(pi)) {
const kind = phase.advance?.kind || ''
if (kind === 'on') return Infinity
if (kind === 'after') total += afterMinutes(phase.advance.after) || 0
}
return total
}
/**
* Does phase `pi` give a timed step back before its time? (§2.2, U-6)
*
* `null`, or `{ longest, floor }` in minutes. Only a run that can END sooner than
* the longest hold counts: teardown is what gives a lease back, not the phase.
*/
export function timedPhaseShortfall(phases, pi, actionById) {
const longest = phaseMinutes(phases?.[pi], actionById)
if (!longest) return null
const floor = runFloorMinutes(phases, pi)
return floor < longest ? { longest, floor } : null
}
/**
* The phase's advance after a timed step was added or changed (§2.2).
*
* A phase with NO advance rule that would give the step back early gets
* `after: '<longest>m'`, visibly, and the author may change it. A phase the
* author already gave a rule keeps it: the warning under the phase says what it
* costs, and overriding an author's choice is not this function's to do.
*/
export function guardedAdvance(phases, pi, actionById) {
const phase = phases?.[pi]
if (!phase || (phase.advance?.kind || '') !== '') return null
const short = timedPhaseShortfall(phases, pi, actionById)
if (!short) return null
return { ...(phase.advance || blankAdvance()), kind: 'after', after: `${Math.ceil(short.longest)}m` }
}
/** "1 minute", "90 minutes", "2 hours". */
export function minutesWord(n) {
if (n >= 120 && n % 60 === 0) return `${n / 60} hours`
return `${n} minute${n === 1 ? '' : 's'}`
}
/** The sentence under a phase that ends a timed step early, or null. */
export function shortfallSentence(phases, pi, actionById) {
const short = timedPhaseShortfall(phases, pi, actionById)
if (!short) return null
const last = pi === (phases || []).length - 1
const ends = short.floor === 0
? (last ? 'This phase ends as soon as its steps are done, and the run with it' : 'The rest of this run can be over as soon as its steps are done')
: (last ? `This phase ends after ${minutesWord(short.floor)}, and the run with it` : `The rest of this run can be over ${minutesWord(short.floor)} after this phase starts`)
return `${ends}; what is held for ${minutesWord(short.longest)} is given back then, not after ${minutesWord(short.longest)}.`
}
/**
* Everything the meter needs out of the form, and nothing else.
*
@@ -734,6 +1055,15 @@ function detailValue(value) {
export const logKindWord = (kind) => KIND_WORDS[kind] || kind
// "20:10", in the viewer's own clock. Time only: the log line it sits in carries
// its own timestamp, and a retry is at most thirty minutes after it.
function clockTime(value) {
if (!value) return ''
const t = new Date(value)
if (Number.isNaN(t.getTime())) return ''
return `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`
}
/**
* One log line as a sentence.
*
@@ -760,14 +1090,20 @@ export function describeLogLine(line) {
return `${line.phase} finished`
case 'step.parked':
return `${d.action} is waiting on a human`
case 'step.retry':
return `${d.action} failed, attempt ${d.attempt} of ${d.of}${d.error ? `: ${d.error}` : ''}`
case 'step.retry': {
// `retryAt` is on every retry line since MODULE_API 1.15.0; a line written
// before it says what it always said.
const at = clockTime(d.retryAt)
return `${d.action} failed, attempt ${d.attempt} of ${d.of}${at ? `, retrying at ${at}` : ''}${d.error ? `: ${d.error}` : ''}`
}
case 'step.status':
return d.control
? `${d.action} → ${d.to}${by} — ${d.control}${d.note || d.reason ? `: ${d.note || d.reason}` : ''}`
: `${d.action} → ${d.to}${d.error ? `: ${d.error}` : ''}`
case 'run.created':
return `Occurrence created from version ${d.version}${d.rehearsal ? ' (rehearsal)' : ''}`
return `Occurrence created from version ${d.version}${d.rehearsal ? ' (rehearsal)' : ''}${
d.source === 'trigger' && d.origin ? ` — ${describeOrigin(d.origin)}` : ''
}`
case 'phase.gate':
return d.kind === 'after'
? `${line.phase} advances ${d.after} after it started`

View File

@@ -97,3 +97,13 @@ export function statusWord(status, scheduledFor, now = Date.now()) {
const at = new Date(scheduledFor).getTime()
return Number.isNaN(at) || at <= now ? 'Did not happen' : 'Cancelled'
}
// A live run's progress line (MODULE_API 1.12.0), as text. Core accepts two
// shapes from a module and interprets neither: a count, "Bandits: 3 of 8 left",
// and a percentage, "The Juggernaut: 62%". Anything else renders nothing.
export function progressText(line) {
if (!line || typeof line.label !== 'string' || !line.label) return ''
if (Number.isInteger(line.left) && Number.isInteger(line.of)) return `${line.label}: ${line.left} of ${line.of} left`
if (typeof line.percent === 'number') return `${line.label}: ${line.percent}%`
return ''
}

View File

@@ -11,6 +11,23 @@
// that the two files can drift, so a test asserts they agree
// (client/test/moduleRegistry.test.js) rather than trusting a bump to remember
// both.
// 1.15.0 — a failed step's `retryAfterMs` (Rust PLAN_REDESIGNS §14.3.13): when
// to try again. Server-side; the run console's retry line now says when. This
// file bumps for the reason at the top.
// 1.14.0 —an action param's `multiple` (Rust PLAN_REDESIGNS §12.3): a param
// that holds several values, drawn by core's step editor as a multi-select.
// Server-side declaration; this file bumps for the reason at the top.
// 1.13.0 — the event step editor (Rust PLAN_REDESIGNS §2): event templates, a
// param's `duration`, a lease's `example` and an option's `note`. All four are
// server-side declarations the editor, core's own page, renders. This file bumps
// for the reason at the top.
// 1.12.0 — an event action's `progress()`: a live run's public page shows how
// its steps stand. Server-side registration; the client half is core's own event
// page rendering the lines. This file bumps for the reason at the top.
// 1.11.0 — `ctx.events.expired({ kind, ref })` and the ledger's `expired` status
// (Rust PLAN_FIXES D183): a module may say the game ended a ledgered resource at
// its own deadline. Server-side only; the run console, which is core's own page,
// shows the new status. This file bumps for the reason at the top.
// 1.10.0 — the event contract opens to modules (EVENTS.md §F, EVENTS_PLAN.md
// Phase 7): a module may register event actions, budget dimensions, leases and
// param option sources. All four are server-side registrations and nothing on
@@ -74,4 +91,4 @@
// but the two halves state ONE version: a module declares a single coreApi range
// and is served one chunk, so a client that claimed 1.0.0 while the server
// answered 1.1.0 would be two answers to one question.
export const MODULE_API_VERSION = '1.10.0'
export const MODULE_API_VERSION = '1.15.0'

View File

@@ -166,7 +166,12 @@ export default function Dashboard() {
className="sans"
style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '13px 18px', borderBottom: '1px solid var(--line-soft)', fontSize: '0.86rem' }}
>
<span style={{ flex: 'none', color: 'var(--accent)', fontSize: '0.66rem', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', width: 110, fontFamily: 'ui-monospace,Menlo,monospace' }}>
{/* `minWidth` rather than `width`: the column still lines up for core's
own short action names, and a longer one — a module's namespaced
action, say `rust.account.unlink.staff` — grows the box instead of
overflowing it and printing on top of the detail beside it. Found
on a live dashboard with a module installed. */}
<span style={{ flex: 'none', color: 'var(--accent)', fontSize: '0.66rem', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', minWidth: 110, fontFamily: 'ui-monospace,Menlo,monospace' }}>
{a.action}
</span>
<span style={{ flex: 1, color: 'var(--text)' }}>{formatDetail(a)}</span>

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,8 @@ import {
runControlsFor,
stepControlsFor,
describeLogLine,
describeParams,
describeOrigin,
} from '../../../lib/eventAuthoring.js'
// Admin → Events → the run console (EVENTS.md §I, Phase 3).
@@ -59,7 +61,7 @@ const STATUS_COLOR = {
completed: '#8fc79a',
}
// The six ledger statuses, in the two groups that matter to a reader: green is
// The seven ledger statuses, in the two groups that matter to a reader: green is
// resolved, amber wants a person. `orphaned` and `drifted` are amber rather than
// red because neither is a fault — one thing vanished, the other was taken by
// somebody with every right to take it — and red is reserved for "this did not
@@ -71,6 +73,9 @@ const RESOURCE_COLOR = {
reverting: '#d9c184',
drifted: '#d9c184',
orphaned: '#d9c184',
// Green, like `reverted`: the game ended it at the deadline it was given, which
// is the plan working (MODULE_API 1.11.0). `orphaned` is the amber one.
expired: '#8fc79a',
}
const RESOURCE_WORD = {
@@ -80,6 +85,7 @@ const RESOURCE_WORD = {
reverted: 'given back',
orphaned: 'gone',
drifted: 'someone else moved it',
expired: 'ended by the game on time',
}
const STEP_COLOR = {
@@ -289,6 +295,13 @@ export default function EventRun() {
{run.rehearsal ? ' · rehearsal' : ''}
{run.concurrencyKey ? ` · key ${run.concurrencyKey}` : ''}
</p>
{/* Why it exists, when a game firing started it (D370). */}
{describeOrigin(run.origin) && (
<p className="sans" style={{ margin: '4px 0 0', fontSize: '0.8rem' }}>
{describeOrigin(run.origin)}
<span className="dim"> · {when(run.origin.occurredAt)}</span>
</p>
)}
</div>
<div style={{ textAlign: 'right' }}>
<div className="sans" style={{ fontSize: '1rem', color: STATUS_COLOR[run.status] || undefined }}>
@@ -651,7 +664,7 @@ export default function EventRun() {
<td className="adm-td" style={{ fontSize: '0.82rem' }}>
<code style={{ fontSize: '0.78rem' }}>{step.actionId}</code>
<div className="dim" style={{ fontSize: '0.74rem', maxWidth: 320, overflowWrap: 'anywhere' }}>
{JSON.stringify(step.params)}
{describeParams(step.params)}
</div>
</td>
<td className="adm-td" style={{ fontSize: '0.82rem', color: STEP_COLOR[step.status] || undefined }}>

View File

@@ -14,13 +14,19 @@
// branch left a failed load spinning for ever with nothing on screen naming the
// problem. Order matters, and the order is error first.
import { useEffect, useState } from 'react'
import { useParams, useSearchParams, Link } from 'react-router-dom'
import PublicLayout from '../../components/PublicLayout.jsx'
import PageHeader from '../../components/PageHeader.jsx'
import { Loading, ErrorState, EmptyState } from '../../components/PageState.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { api } from '../../api/client.js'
import { eventDateTime, statusWord } from '../../lib/eventCalendar.js'
import { eventDateTime, statusWord, progressText } from '../../lib/eventCalendar.js'
// How often a live event's progress lines are read again while the page is open.
// The server caches each run's answer for five seconds, so this is the reader's
// cadence, not load on the game.
const PROGRESS_REFRESH_MS = 15_000
export default function EventPage() {
const { slug } = useParams()
@@ -28,6 +34,27 @@ export default function EventPage() {
const run = params.get('run')
const { loading, error, data } = useAsync(() => api.publicEvent(slug, run), [slug, run])
// The live occurrence's progress (MODULE_API 1.12.0), re-read on a timer while
// it is live. Only the lines are replaced: re-running the page's own fetch
// would blank the page to a spinner every fifteen seconds.
const [progress, setProgress] = useState(null)
const live = Boolean(data && data.event && data.event.live)
useEffect(() => {
setProgress(null)
if (!live) return undefined
let active = true
const timer = setInterval(() => {
api
.publicEvent(slug, run)
.then((fresh) => active && setProgress(fresh?.event?.current?.progress || []))
.catch(() => {})
}, PROGRESS_REFRESH_MS)
return () => {
active = false
clearInterval(timer)
}
}, [slug, run, live])
if (error) {
return (
<PublicLayout section="website">
@@ -91,6 +118,16 @@ export default function EventPage() {
the event is never published. */}
{event.current.phase || 'Under way'}
</div>
{/* How it stands, in the words the steps' modules chose. Core
renders the two shapes it accepts and interprets neither. */}
{(progress || event.current.progress || []).map((line, i) => {
const text = progressText(line)
return text ? (
<div key={i} className="sans" style={{ marginTop: 4 }}>
{text}
</div>
) : null
})}
</>
) : event.next ? (
<>

View File

@@ -347,6 +347,21 @@ test('the log lines a run produces all render as something', () => {
}
})
test('a retry line says when it will run (MODULE_API 1.15.0), and an older line still reads', () => {
// Built from local parts so the assertion holds in any timezone the suite runs in.
const at = new Date(2026, 9, 15, 20, 10, 0)
const text = describeLogLine({
kind: 'step.retry',
detail: { action: 'rust.dt.start', attempt: 1, of: 3, error: 'not ready yet', retryAt: at.toISOString() },
})
assert.equal(text, 'rust.dt.start failed, attempt 1 of 3, retrying at 20:10: not ready yet')
const before = describeLogLine({ kind: 'step.retry', detail: { action: 'core.announce', attempt: 2, of: 3 } })
assert.equal(before, 'core.announce failed, attempt 2 of 3')
const junk = describeLogLine({ kind: 'step.retry', detail: { action: 'a', attempt: 1, of: 3, retryAt: 'soon' } })
assert.equal(junk, 'a failed, attempt 1 of 3', 'an unreadable time is left out, not shown as NaN')
})
// ── The one log line core did not compose (Phase 15) ──────────────────────
test('a module detail line renders the module keys, not the kind id', () => {

View File

@@ -9,7 +9,7 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { eventTime, eventDateTime, readerDayLabel, statusWord } from '../src/lib/eventCalendar.js'
import { eventTime, eventDateTime, readerDayLabel, statusWord, progressText } from '../src/lib/eventCalendar.js'
// 2026-09-12T00:00Z is 2026-09-11 20:00 in New York — deliberately an instant
// whose DATE differs between the two zones, which is what makes the split
@@ -87,3 +87,11 @@ test('the other three words do not depend on the clock at all', () => {
test('an unreadable instant falls to the past-tense word rather than throwing', () => {
assert.equal(statusWord('cancelled', 'not a date', NOW), 'Did not happen')
})
test('a progress line is a count or a percent, and nothing else renders (MODULE_API 1.12.0)', () => {
assert.equal(progressText({ label: 'Bandits', left: 3, of: 8 }), 'Bandits: 3 of 8 left')
assert.equal(progressText({ label: 'The Juggernaut', percent: 62 }), 'The Juggernaut: 62%')
assert.equal(progressText({ label: 'Odd' }), '')
assert.equal(progressText({ left: 1, of: 2 }), '')
assert.equal(progressText(null), '')
})

View File

@@ -0,0 +1,94 @@
// A param that holds several values (MODULE_API 1.14.0; Rust PLAN_REDESIGNS
// §12.3): what the multi-select stores, when it gives way to JSON, and how the
// run console reads a list back.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
blankStep,
paramsMode,
PARAM_FORM,
PARAM_JSON,
listValue,
setParamList,
addToList,
filterOptions,
missingParams,
describeParams,
} from '../src/lib/eventAuthoring.js'
const LEND = {
id: 'test.perm.lend',
params: [
{ name: 'server', type: 'string', required: true, example: 'main' },
{ name: 'perms', type: 'string', required: true, example: 'nightvision.allowed', multiple: true, max: 3 },
{ name: 'ids', type: 'int', required: false, example: 7, multiple: true, max: 20 },
],
}
const step = (params) => ({ actionId: LEND.id, paramsText: JSON.stringify(params) })
test('a new step holds the example as a list of one', () => {
const fresh = JSON.parse(blankStep(LEND).paramsText)
assert.deepEqual(fresh.perms, ['nightvision.allowed'])
assert.deepEqual(fresh.ids, [7])
assert.equal(fresh.server, 'main')
})
test('a list is a value the form can hold; a structure in it is not', () => {
assert.equal(paramsMode(step({ perms: ['a', 'b'] }), LEND).mode, PARAM_FORM)
assert.equal(paramsMode(step({ perms: 'a' }), LEND).mode, PARAM_FORM)
const nested = paramsMode(step({ perms: [{ a: 1 }] }), LEND)
assert.equal(nested.mode, PARAM_JSON)
assert.match(nested.reason, /"perms" holds a structure/)
// A list against a single-value param still forces JSON, as before 1.14.0.
assert.equal(paramsMode(step({ server: ['main'] }), LEND).mode, PARAM_JSON)
})
test('listValue reads a bare value as a list of one, and nothing as none', () => {
assert.deepEqual(listValue(['a', 'b']), ['a', 'b'])
assert.deepEqual(listValue('a'), ['a'])
for (const empty of [undefined, null, '']) assert.deepEqual(listValue(empty), [])
})
test('setParamList coerces, drops duplicates in order, and removes an empty list', () => {
const s = step({ server: 'main' })
assert.deepEqual(JSON.parse(setParamList(s, 'ids', ['3', '1', '3'], 'int')).ids, [3, 1])
assert.deepEqual(JSON.parse(setParamList(s, 'perms', ['b', 'a', 'b', ''], 'string')).perms, ['b', 'a'])
const cleared = JSON.parse(setParamList(step({ server: 'main', perms: ['a'] }), 'perms', [], 'string'))
assert.equal('perms' in cleared, false)
// A box that does not parse is handed back untouched.
assert.equal(setParamList({ paramsText: '{nope' }, 'perms', ['a'], 'string'), '{nope')
})
test('addToList ignores blanks and repeats, and refuses past max in words', () => {
assert.deepEqual(addToList(['a'], ' b ', 3).list, ['a', 'b'])
assert.deepEqual(addToList(['a'], 'a', 3).list, ['a'])
assert.deepEqual(addToList(['a'], ' ', 3).list, ['a'])
assert.match(addToList(['a', 'b', 'c'], 'd', 3).refused, /at most 3/)
})
test('filterOptions matches value, label or group and keeps the source order', () => {
const options = [
{ value: 'nightvision.allowed', label: 'nightvision.allowed', group: 'NightVision' },
{ value: 'betterchat.color', label: 'betterchat.color', group: 'BetterChat' },
{ value: 'kits.vip', label: 'kits.vip', group: 'Kits' },
]
assert.equal(filterOptions(options, '').length, 3)
assert.deepEqual(filterOptions(options, 'NIGHT').map((o) => o.value), ['nightvision.allowed'])
assert.deepEqual(filterOptions(options, 'chat').map((o) => o.value), ['betterchat.color'])
assert.deepEqual(filterOptions(options, 'i').map((o) => o.value), ['nightvision.allowed', 'kits.vip'])
})
test('an empty required list is missing', () => {
assert.deepEqual(missingParams(step({ server: 'main', perms: [] }), LEND), ['perms'])
assert.deepEqual(missingParams(step({ server: 'main' }), LEND), ['perms'])
assert.deepEqual(missingParams(step({ server: 'main', perms: ['a'] }), LEND), [])
})
test('the run console shows a list as its values joined by commas', () => {
assert.equal(
describeParams({ server: 'main', perms: ['nightvision.allowed', 'betterchat.color'], confirm: true }),
'server: main · perms: nightvision.allowed, betterchat.color · confirm: true',
)
assert.equal(describeParams({ where: { a: 1 } }), 'where: {"a":1}')
assert.equal(describeParams(null), '')
})

View File

@@ -0,0 +1,110 @@
// A definition's trigger starts in the editor, and a run's origin on the
// console (Rust PLAN_REDESIGNS §14.3.12, D370). The server decides; these prove
// the form carries what it is given and the sentences read right.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
formFromDefinition,
payloadFromForm,
blankStart,
startsFormFrom,
startsPayload,
isStartableTrigger,
describeOrigin,
describeTriggerStarts,
describeLogLine,
} from '../src/lib/eventAuthoring.js'
const TRIGGER = {
id: 'rust.world.bradley_destroyed',
label: 'Bradley destroyed',
variables: [
{ name: 'server', type: 'string' },
{ name: 'kills', type: 'int' },
],
}
const triggersById = new Map([[TRIGGER.id, TRIGGER]])
const definition = (starts) => ({
title: 'Launch Site Lockdown',
spec: {
schedule: { kind: 'manual' },
...(starts ? { starts } : {}),
phases: [{ key: 'main', label: 'Main', steps: [] }],
},
})
test('a stored start round-trips through the form unchanged', () => {
const starts = [{ on: TRIGGER.id, where: { variable: 'server', cmp: 'eq', value: 'main' }, cooldown: '2h' }]
const form = formFromDefinition(definition(starts))
assert.equal(form.starts.length, 1)
assert.equal(form.starts[0].whereRows.length, 1)
const built = payloadFromForm(form, { triggersById })
assert.equal(built.ok, true)
assert.deepEqual(built.payload.spec.starts, starts)
})
test('no starts is no key, as the server stores it', () => {
const built = payloadFromForm(formFromDefinition(definition()), { triggersById })
assert.equal('starts' in built.payload.spec, false)
assert.deepEqual(formFromDefinition(definition()).starts, [])
})
test('a half-added row is dropped, a blank cooldown is the default, a literal takes the declared type', () => {
const rows = [
blankStart(),
{ ...blankStart(), on: TRIGGER.id, cooldown: ' ', whereRows: [{ variable: 'kills', cmp: 'gte', value: '2' }] },
]
const errors = []
const out = startsPayload(rows, errors, triggersById)
assert.deepEqual(errors, [])
assert.deepEqual(out, [{ on: TRIGGER.id, cooldown: '30m', where: { variable: 'kills', cmp: 'gte', value: 2 } }])
})
test('a nested condition the builder cannot draw is posted back verbatim', () => {
const where = { op: 'and', nodes: [{ variable: 'server', cmp: 'eq', value: 'main' }, { op: 'or', nodes: [{ variable: 'kills', cmp: 'gt', value: 1 }, { variable: 'kills', cmp: 'lt', value: 0 }] }] }
const [row] = startsFormFrom([{ on: TRIGGER.id, where, cooldown: '0m' }])
assert.equal(row.whereEditable, false)
assert.deepEqual(startsPayload([row], [], triggersById), [{ on: TRIGGER.id, cooldown: '0m', where }])
})
test('core\'s own lifecycle triggers are not offered', () => {
assert.equal(isStartableTrigger({ id: 'event.run.started' }), false)
assert.equal(isStartableTrigger(TRIGGER), true)
})
test('the origin sentence', () => {
assert.equal(describeOrigin(null), null)
assert.equal(
describeOrigin({
kind: 'trigger',
triggerId: TRIGGER.id,
label: 'Bradley destroyed',
matched: 'server is "main"',
variables: { server: 'main', grid: 'G8', _truncated: true },
}),
'Started because “Bradley destroyed” fired (matching server is "main"): server main · grid G8',
)
assert.equal(describeOrigin({ kind: 'trigger', triggerId: 'x.y', variables: {} }), 'Started because “x.y” fired')
})
test('the editor\'s ignored-firings line', () => {
assert.equal(describeTriggerStarts(null), null)
assert.equal(
describeTriggerStarts({ lastRunId: 12, ignoredRunning: 2, ignoredCooldown: 1, ignoredUnverified: 0 }),
'Last started run #12; since then 2 firings ignored while a run was going, 1 firing ignored in the cooldown.',
)
assert.equal(
describeTriggerStarts({ lastRunId: null, ignoredRunning: 0, ignoredCooldown: 0, ignoredUnverified: 1 }),
'No run started by a trigger yet; since then 1 firing ignored because the published version is not verified.',
)
assert.equal(describeTriggerStarts({ lastRunId: 3 }), 'Last started run #3.')
})
test('the audit line names a trigger start', () => {
const line = describeLogLine({
kind: 'run.created',
detail: { version: 2, source: 'trigger', origin: { kind: 'trigger', label: 'Bradley destroyed', variables: { grid: 'G8' } } },
})
assert.equal(line, 'Occurrence created from version 2 — Started because “Bradley destroyed” fired: grid G8')
})

View File

@@ -0,0 +1,144 @@
// The step editor's own rules (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2): which
// control a field gets, which required fields are empty, and whether a phase
// gives a timed step back before its time is up.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
boolValue,
isSegmentable,
noteFor,
missingParams,
afterMinutes,
stepMinutes,
runFloorMinutes,
timedPhaseShortfall,
guardedAdvance,
shortfallSentence,
minutesWord,
blankAdvance,
} from '../src/lib/eventAuthoring.js'
const LEASE_ACTION = {
id: 'core.lease',
params: [
{ name: 'lease', type: 'string', required: true },
{ name: 'value', type: 'string', required: true },
{ name: 'target', type: 'string', required: false },
{ name: 'minutes', type: 'int', required: true, duration: 'minutes' },
],
}
const SAY = { id: 'test.say', params: [{ name: 'message', type: 'string', required: true }] }
const actionById = new Map([[LEASE_ACTION.id, LEASE_ACTION], [SAY.id, SAY]])
const step = (actionId, params) => ({ actionId, paramsText: JSON.stringify(params) })
const lease = (minutes) => step('core.lease', { lease: 'x.flag', value: 'true', minutes })
const phase = (steps, advance = blankAdvance()) => ({ key: 'p', label: 'P', steps, advance })
const after = (a) => ({ ...blankAdvance(), kind: 'after', after: a })
const on = () => ({ ...blankAdvance(), kind: 'on', on: 'x.happened' })
test('a lease\'s "true" is a boolean to the control', () => {
assert.equal(boolValue('true'), true)
assert.equal(boolValue(false), false)
assert.equal(boolValue(''), null)
assert.equal(boolValue(undefined), null)
})
test('two or three answered choices are buttons; a search or a long list is not', () => {
const ok = (n, extra = {}) => ({ state: 'ok', options: Array.from({ length: n }, (_, i) => ({ value: String(i) })), ...extra })
assert.equal(isSegmentable(ok(2)), true)
assert.equal(isSegmentable(ok(3)), true)
assert.equal(isSegmentable(ok(1)), false)
assert.equal(isSegmentable(ok(4)), false)
assert.equal(isSegmentable(ok(2, { searchable: true })), false)
assert.equal(isSegmentable({ state: 'failed', options: [] }), false)
})
test('the chosen option\'s note, and nothing for one without', () => {
const entry = { state: 'ok', options: [{ value: 'vip', note: '9 of 41 used it up' }, { value: 'free' }] }
assert.equal(noteFor(entry, 'vip'), '9 of 41 used it up')
assert.equal(noteFor(entry, 'free'), null)
assert.equal(noteFor(entry, ''), null)
})
test('required and empty, including the target a targeted lease needs', () => {
assert.deepEqual(missingParams(step('test.say', {}), SAY), ['message'])
assert.deepEqual(missingParams(step('test.say', { message: 'hi' }), SAY), [])
const leases = new Map([['x.perm', { id: 'x.perm', target: { label: 'Group' } }], ['x.flag', { id: 'x.flag' }]])
assert.deepEqual(
missingParams(step('core.lease', { lease: 'x.perm', value: 'true', minutes: 5 }), LEASE_ACTION, leases),
['target'],
)
assert.deepEqual(missingParams(lease(5), LEASE_ACTION, leases), [])
// A step whose JSON does not parse is the JSON box's to report, not this.
assert.deepEqual(missingParams({ actionId: 'test.say', paramsText: '{' }, SAY), [])
})
test('the server\'s after grammar, in minutes', () => {
assert.equal(afterMinutes('30m'), 30)
assert.equal(afterMinutes('2h'), 120)
assert.equal(afterMinutes('90s'), 1.5)
assert.equal(afterMinutes('1d'), 1440)
assert.equal(afterMinutes('soon'), null)
})
test('a step is as long as its longest declared duration', () => {
assert.equal(stepMinutes(lease(10), LEASE_ACTION), 10)
assert.equal(stepMinutes(step('test.say', { message: 'x' }), SAY), 0)
assert.equal(stepMinutes(lease('ten'), LEASE_ACTION), 0)
})
test('the run\'s floor counts every later phase, and a game trigger is unbounded', () => {
const phases = [phase([]), phase([], after('5m')), phase([], after('1h'))]
assert.equal(runFloorMinutes(phases, 0), 65)
assert.equal(runFloorMinutes(phases, 2), 60)
assert.equal(runFloorMinutes([phase([]), phase([], on())], 0), Infinity)
})
test('U-6: a one-phase event with no rule gives a 10-minute lease back at once', () => {
const phases = [phase([lease(10)])]
assert.deepEqual(timedPhaseShortfall(phases, 0, actionById), { longest: 10, floor: 0 })
assert.equal(
shortfallSentence(phases, 0, actionById),
'This phase ends as soon as its steps are done, and the run with it; what is held for 10 minutes is given back then, not after 10 minutes.',
)
})
test('a phase with no rule is given after: <longest>, and a chosen rule is left alone', () => {
const advance = guardedAdvance([phase([lease(10)])], 0, actionById)
assert.equal(advance.kind, 'after')
assert.equal(advance.after, '10m')
// The author's 5 minutes stays; the sentence says what it costs instead.
const chosen = [phase([lease(10)], after('5m'))]
assert.equal(guardedAdvance(chosen, 0, actionById), null)
assert.equal(
shortfallSentence(chosen, 0, actionById),
'This phase ends after 5 minutes, and the run with it; what is held for 10 minutes is given back then, not after 10 minutes.',
)
})
test('later phases long enough to cover the hold are no shortfall at all', () => {
const phases = [phase([lease(10)]), phase([], after('15m'))]
assert.equal(timedPhaseShortfall(phases, 0, actionById), null)
assert.equal(guardedAdvance(phases, 0, actionById), null)
assert.equal(shortfallSentence(phases, 0, actionById), null)
// A later phase that waits on the game cannot be counted, and is not warned about.
assert.equal(timedPhaseShortfall([phase([lease(10)]), phase([], on())], 0, actionById), null)
const short = [phase([lease(10)]), phase([], after('3m'))]
assert.match(shortfallSentence(short, 0, actionById), /^The rest of this run can be over 3 minutes after this phase starts;/)
})
test('an untimed phase is never touched', () => {
const phases = [phase([step('test.say', { message: 'x' })])]
assert.equal(guardedAdvance(phases, 0, actionById), null)
assert.equal(shortfallSentence(phases, 0, actionById), null)
})
test('minutes read as words', () => {
assert.equal(minutesWord(1), '1 minute')
assert.equal(minutesWord(45), '45 minutes')
assert.equal(minutesWord(120), '2 hours')
assert.equal(minutesWord(90), '90 minutes')
})

View File

@@ -2560,7 +2560,7 @@ CREATE TABLE IF NOT EXISTS event_run_resources (
-- defensible. This column is core's copy of that promise, for the console and
-- for the boot-time check.
lease_until DATETIME NULL,
status ENUM('pending','confirmed','reverting','reverted','orphaned','drifted')
status ENUM('pending','confirmed','reverting','reverted','orphaned','drifted','expired')
NOT NULL DEFAULT 'pending',
-- Bounded like a step's `attempts`, and for the same reason: a revert that can
-- never succeed must become visible rather than cycling for ever. Engagement
@@ -2587,6 +2587,14 @@ CREATE TABLE IF NOT EXISTS event_run_resources (
INDEX idx_evres_live (status, lease_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- MODULE_API 1.11.0 (Rust PLAN_FIXES D183): `expired`, the game ending a resource
-- at its own deadline, for databases created before it. Terminal, so `live_marker`
-- releases the target. MODIFY has no IF NOT EXISTS form, but re-declaring the same
-- ENUM is an idempotent no-op -- checked against MariaDB 11.8 with the stored
-- `live_marker` column depending on it -- so it is safe on every boot.
ALTER TABLE event_run_resources MODIFY COLUMN status
ENUM('pending','confirmed','reverting','reverted','orphaned','drifted','expired') NOT NULL DEFAULT 'pending';
-- §K's last bound: "a scheduled definition that has never been verified is the
-- case worth refusing to start". A version is immutable, so a dry run that passed
-- against it stays true — which is what makes the pass a property of the VERSION
@@ -2696,3 +2704,43 @@ ALTER TABLE event_runs ADD COLUMN IF NOT EXISTS results_published_at DATETIME NU
-- that no longer resolves answers that honestly.
ALTER TABLE announce_jobs ADD COLUMN IF NOT EXISTS run_id BIGINT NULL;
ALTER TABLE announce_jobs ADD INDEX IF NOT EXISTS idx_announce_run (run_id);
-- ── A trigger can start a run (Rust PLAN_REDESIGNS §14.3.12, D370) ─────────
-- Why a run exists, when a game firing started it: the trigger, when it fired,
-- its subject and its variables, so the console can say "started because a
-- champion boss is up at Abyss" and the audit can say what. NULL for a run an
-- admin or the schedule started, which `run.created`'s `source` already says.
--
-- A column rather than only a log line because the run log is pruned and the
-- run is not, and "why did this run happen" outlives "what did each step do".
ALTER TABLE event_runs ADD COLUMN IF NOT EXISTS origin JSON NULL;
-- One row per definition that a trigger has tried to start: the cooldown's
-- clock, the claim that makes "one run at a time" true, and the count of
-- firings it ignored, which the editor shows ("2 firings ignored while
-- running").
--
-- **The claim is a conditional UPDATE on this row**, the event_run_budget
-- argument once more: two firings arriving together each try it, and the
-- cooldown, the one-at-a-time check and a stale-claim guard are all in its
-- WHERE, so exactly one of them owns the start. `claimed_at` is held only
-- between the claim and the run row existing — a minute is a crashed process,
-- not a slow insert.
--
-- The counts are since the LAST trigger-started run, and a new start zeroes
-- them: what an operator asks is "is it ignoring things right now", and a
-- lifetime total cannot answer that.
CREATE TABLE IF NOT EXISTS event_trigger_starts (
definition_id INT NOT NULL PRIMARY KEY,
claimed_at DATETIME NULL,
last_started_at DATETIME NULL, -- the firing's time, which is the run's scheduled_for
last_run_id BIGINT NULL,
ignored_running INT NOT NULL DEFAULT 0,
ignored_cooldown INT NOT NULL DEFAULT 0,
ignored_unverified INT NOT NULL DEFAULT 0,
last_ignored_at DATETIME NULL,
last_ignored_reason VARCHAR(32) NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT fk_evtrig_def FOREIGN KEY (definition_id) REFERENCES event_definitions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@@ -1,6 +1,6 @@
{
"_comment": "Generated event-trigger inventory - the authoritative freeze of CORE's engagement contract (docs/website/ENGAGEMENT.md 4.3). Regenerate with `npm run engagement:manifest` in website/server. A renamed variable, a changed type or a widened ceiling breaks stored templates and rules, so the diff here is the review signal. A module ships its own copy in its bundle; this file never contains one.",
"moduleApiVersion": "1.10.0",
"moduleApiVersion": "1.15.0",
"triggers": [
{
"id": "event.phase.changed",

View File

@@ -545,6 +545,15 @@
"requireAuth"
]
},
{
"method": "POST",
"path": "/api/v1/admin/events/catalog/templates/:templateId",
"handlers": 2,
"gates": [
"noindex",
"requireAuth"
]
},
{
"method": "POST",
"path": "/api/v1/admin/events/price",
@@ -2464,9 +2473,10 @@
{
"method": "GET",
"path": "/api/v1/public/events/:slug",
"handlers": 2,
"handlers": 3,
"gates": [
"siteMode"
"siteMode",
"optionalAuth"
]
},
{

View File

@@ -241,6 +241,10 @@
"method": "GET",
"path": "/api/v1/admin/events/catalog/options/:sourceId"
},
{
"method": "POST",
"path": "/api/v1/admin/events/catalog/templates/:templateId"
},
{
"method": "POST",
"path": "/api/v1/admin/events/price"

View File

@@ -137,14 +137,14 @@ const ACTIONS = [
name: 'title',
type: 'string',
required: false,
example: 'The gates of Britain open at dusk',
example: 'The gates open at dusk',
description: 'Optional heading, for legs that render one.',
},
{
name: 'body',
type: 'string',
required: true,
example: 'A caravan has been sighted on the road east of Cove.',
example: 'A caravan has been sighted on the east road.',
description: 'The announcement itself. Plain text.',
},
],
@@ -250,7 +250,7 @@ const ACTIONS = [
name: 'instruction',
type: 'string',
required: true,
example: 'Open the north gate and read the herald script in Britain bank.',
example: 'Open the north gate and read the herald script in the town square.',
description: 'What the staff member is being asked to do.',
},
{
@@ -306,7 +306,10 @@ const ACTIONS = [
name: 'lease',
type: 'string',
required: true,
example: 'uo.rate.skillgain',
// Game-neutral (Rust PLAN_REDESIGNS §0.9): this was a UO rate, shown to
// every deployment's authors. The editor now draws the chosen lease's own
// form and examples (MODULE_API 1.13.0), so this is only ever a fallback.
example: 'mygame.rate.gather',
source: 'core.options.leases',
description: 'Which declared value to borrow.',
},
@@ -347,6 +350,10 @@ const ACTIONS = [
type: 'int',
required: true,
example: 120,
// A timed step (MODULE_API 1.13.0): the editor keeps the phase open at
// least this long, because teardown gives the value back when the run
// ends, whatever this says.
duration: 'minutes',
description: 'How long to hold it. Core refuses more than the lease allows.',
},
],

View File

@@ -144,7 +144,9 @@ function priceOf(action, params) {
function dimensionsOf(action) {
const params = {}
for (const p of action?.params || []) {
if (p.example !== undefined && p.example !== null) params[p.name] = p.example
// A `multiple` param's example is one value and `cost()` is handed a list
// (1.14.0), so it is priced as a list of one.
if (p.example !== undefined && p.example !== null) params[p.name] = p.multiple ? [p.example] : p.example
}
const priced = priceOf(action, params)
return priced ? Object.keys(priced).sort() : []

View File

@@ -320,6 +320,16 @@ async function sweep() {
// cleanup, whose counters were spent deliberately.
const candidates = await resourcesDb.runsNeedingCleanup(CLEANUP_RUN_BATCH, MAX_REVERT_ATTEMPTS)
let swept = 0
// **A finished run with nothing left to give back is complete** (MODULE_API
// 1.11.0). The scan above joins on an unresolved row, and until `expired` no
// run could end `pending` without one. Now a zone can expire while its run is
// still going — `expireResource` leaves a live run's status to its terminal
// path — and when that run ends, nothing in the scan would ever select it:
// `pending` for ever. Found by the step-2 walk, run 46.
for (const runId of await resourcesDb.finishedRunsWithNothingLeft(CLEANUP_RUN_BATCH)) {
if (await runsDb.setCleanupStatus(runId, 'complete', ['pending'])) swept += 1
}
for (const candidate of candidates) {
if (!runsDb.TERMINAL.includes(candidate.status)) continue
try {
@@ -427,6 +437,64 @@ async function reconcileAll() {
return out
}
// The bounds on what a module may name. They are the columns' own: a longer
// value cannot be a row, so it is refused rather than truncated into a match
// against somebody else's.
const MAX_KIND = 64
const MAX_REF = 190
/**
* The game ended one of this module's resources by itself, as it was told to —
* `ctx.events.expired({ kind, ref })`, MODULE_API 1.11.0 (Rust PLAN_FIXES D183).
*
* **Expired is not orphaned, and the difference is the reason this exists.** A
* Rust zone is created with a deadline and the game erases it when the deadline
* passes, without being asked again — the fail-safe that makes an unattended
* world change defensible. Until a module could say so, core learned of it only
* through reconcile, which files it as `orphaned`: a thing that vanished while
* nobody was looking, amber on the console and still claimable for a revert.
* An expiry is the plan working, so it is terminal and green like `reverted`.
*
* `owner` is bound by the loader, never taken from the module's arguments, for
* `reconcile`'s reason: without the binding a module could close another
* module's rows. Answers `{ expired }`; nothing matching is `{ expired: 0 }`,
* because a module hears expiries of things no run ledgered too.
*/
async function expireResource(owner, { kind, ref } = {}) {
if (typeof kind !== 'string' || !kind || kind.length > MAX_KIND) return { expired: 0 }
if (typeof ref !== 'string' || !ref || ref.length > MAX_REF) return { expired: 0 }
const rows = await resourcesDb.expirableByTarget(owner, kind, ref)
const runs = new Set()
let expired = 0
for (const row of rows) {
if (!(await resourcesDb.markExpired(row.id, 'the game ended it at its deadline'))) continue
expired += 1
runs.add(row.run_id)
await logDb.write({
runId: row.run_id,
kind: 'resource.expired',
detail: { module: owner, resource: `${row.kind}:${row.ref}` },
})
}
// A finished run whose last unresolved row this was has nothing left to clean
// up. The sweep would settle a `pending` one by itself, but not an
// `incomplete` one — that status takes a run out of the sweep's scan, and it
// would go on saying "not finished" about a ledger that is. A run still in
// flight is left alone: its own terminal path computes the status.
for (const runId of runs) {
const run = await runsDb.getById(runId)
if (!run || !runsDb.TERMINAL.includes(run.status)) continue
if ((await resourcesDb.unresolvedCount(runId)) === 0) {
await runsDb.setCleanupStatus(runId, 'complete', ['pending', 'incomplete'])
}
}
return { expired }
}
module.exports = {
MAX_REVERT_ATTEMPTS,
classifyRevert,
@@ -434,4 +502,5 @@ module.exports = {
sweep,
reconcileModule,
reconcileAll,
expireResource,
}

View File

@@ -44,6 +44,38 @@ const MAX_HOLD_SECONDS = 7 * 24 * 60 * 60
// rendered half of one would be a second bug on top of the first.
const MAX_DETAIL_BYTES = 4096
// The bounds on a failure's `retryAfterMs`, in milliseconds (MODULE_API 1.15.0,
// Rust PLAN_REDESIGNS §14.3.13, D371). One minute to thirty. **Clamped, never
// refused**: it is the module's hint about its own verb — "the treasure is still
// warming up, try in ten minutes" — not an author's value, so a module that says
// five seconds or five hours gets the nearest bound rather than a failed step.
// The floor is the flat delay's own default, so no hint can make a retry come
// sooner than an unhinted one would on a stock deployment; the ceiling keeps
// `MAX_ATTEMPTS` tries of a step inside an hour and a half of the moment the
// event was about.
const MIN_RETRY_AFTER_MS = 60_000
const MAX_RETRY_AFTER_MS = 30 * 60_000
/**
* A failure's `retryAfterMs`, clamped, or null for "use the flat delay".
*
* A value that is not a number at all is the hint being absent rather than
* wrong: it is dropped and logged, the step retries on the flat delay, and
* nothing about the failure changes — the same posture as a bad `detail`.
*/
function safeRetryAfter(value, actionId) {
if (value === undefined || value === null) return null
const n = typeof value === 'number' ? value : Number.NaN
if (!Number.isFinite(n)) {
log.warn('event action answered a retryAfterMs that is not a number; using the flat delay', {
action: actionId,
retryAfterMs: String(value).slice(0, 40),
})
return null
}
return Math.min(MAX_RETRY_AFTER_MS, Math.max(MIN_RETRY_AFTER_MS, Math.round(n)))
}
/**
* A module's own account of what a successful step actually did.
*
@@ -127,7 +159,7 @@ function withDeadline(fn, ms, actionId) {
/**
* Turn a raw `perform()` answer into
* `{ outcome, error?, holdSeconds?, resources?, participants? }`.
* `{ outcome, error?, retryAfterMs?, holdSeconds?, resources?, participants? }`.
*
* Exported and pure, so the classification rules are testable without a registry,
* a database or a clock — which matters because they are the rules that decide
@@ -150,10 +182,13 @@ function classify(result, actionId) {
// says `retry: false`, and an envelope that forgot to say anything gets the
// benefit of the doubt on the transient question but not on the success one.
const retry = result.retry !== false
return {
outcome: retry ? 'retry' : 'terminal',
error: result.error ? String(result.error) : `${actionId} refused`,
}
const error = result.error ? String(result.error) : `${actionId} refused`
if (!retry) return { outcome: 'terminal', error }
// **When to try again** is the module's to suggest and core's to bound. Read
// on the retry shape only: a terminal failure is never attempted again, so a
// delay beside `retry: false` describes nothing.
const retryAfterMs = safeRetryAfter(result.retryAfterMs, actionId)
return retryAfterMs === null ? { outcome: 'retry', error } : { outcome: 'retry', error, retryAfterMs }
}
// ── The two success shapes that are not "finished" ──
@@ -250,4 +285,15 @@ async function dispatchStep(step, { run, actor = null, verify = false } = {}) {
return classification
}
module.exports = { dispatchStep, classify, withDeadline, safeDetail, OUTCOMES, MAX_HOLD_SECONDS, MAX_DETAIL_BYTES }
module.exports = {
dispatchStep,
classify,
withDeadline,
safeDetail,
safeRetryAfter,
OUTCOMES,
MAX_HOLD_SECONDS,
MAX_DETAIL_BYTES,
MIN_RETRY_AFTER_MS,
MAX_RETRY_AFTER_MS,
}

View File

@@ -0,0 +1,188 @@
// ── A live run's progress lines ────────────────────────────────────────────
//
// EVENTS.md §I and MODULE_API 1.12.0. While a run is live, its public page can
// say how it stands — "Bandits: 3 of 8 left", "The Juggernaut: 62%" — and only
// the module that carried out a step knows the answer. So an action may declare
// `progress(envelope)`, and this file asks each step of the run whose action has
// one.
//
// **Core never interprets a line.** It accepts exactly two shapes, a count and a
// percentage, each with a label, and renders them as text. Core cannot know what
// a "bandit" is, and does not need to: it knows "label: left of total" and
// "label: percent", which serve any game, and a UO module could fill them for its
// own actions without a word of this file changing (D305).
//
// **Nothing here may hurt the page that asked.** A public event page is read by
// anybody, so every failure — a module that throws, answers late, answers
// nonsense or is uninstalled — is a line that is not shown, and a log line. The
// page always renders. That is `registerTeamProvider`'s posture rather than
// `dispatch.js`'s: a missing progress line costs a reader one sentence, and a page
// that errored would cost them the event.
//
// **One answer per run and viewer level, for a few seconds.** A busy page is
// read by many people at once, and each read reaching the game through a module
// would turn the audience into load. The module's own caches (Rust's map answer)
// sit behind this one; this one bounds how often core asks at all.
const registries = require('../modules/registries')
const stepsDb = require('../model/events/eventRunSteps.db')
const resourcesDb = require('../model/events/eventRunResources.db')
const { withDeadline } = require('./dispatch')
const log = require('../utils/logger')('events')
// The deadline for one `progress()` call. Short, because a reader is waiting on
// it: the page renders without a late line rather than waiting for it.
const PROGRESS_BUDGET_MS = 2000
// How long one run's lines are reused for, per viewer.
const CACHE_MS = 5000
// The bound on a label, in characters. A label is a phrase beside a number.
const MAX_LABEL = 80
// The bound on lines per run. A run with more Place steps than this has a page
// that is a list of numbers, and the cap keeps a module bug from becoming a wall.
const MAX_LINES = 20
// The ledger statuses that still mean "this run's".
const HELD = new Set(resourcesDb.HELD)
/**
* One module answer as a line, or null. Pure and exported: the two shapes are the
* contract, and anything else is dropped rather than repaired.
*/
function toLine(answer, actionId) {
if (answer === null || answer === undefined) return null
if (typeof answer !== 'object' || Array.isArray(answer)) {
log.warn('event progress is not an object', { action: actionId })
return null
}
const label = typeof answer.label === 'string' ? answer.label.trim() : ''
if (!label || label.length > MAX_LABEL) {
log.warn('event progress has a bad label', { action: actionId })
return null
}
const hasCount = answer.left !== undefined || answer.of !== undefined
const hasPercent = answer.percent !== undefined
if (hasCount === hasPercent) {
log.warn('event progress must be a count or a percent', { action: actionId })
return null
}
if (hasCount) {
const { left, of } = answer
if (!Number.isInteger(left) || !Number.isInteger(of) || left < 0 || of < 1 || left > of) {
log.warn('event progress has a bad count', { action: actionId })
return null
}
return { label, left, of }
}
const percent = Number(answer.percent)
if (typeof answer.percent !== 'number' || !Number.isFinite(percent) || percent < 0 || percent > 100) {
log.warn('event progress has a bad percent', { action: actionId })
return null
}
return { label, percent: Math.round(percent) }
}
/** run id + viewer key → { at, lines } and { pending } while one is in flight. */
const cache = new Map()
// A key per reader, so the map is pruned of answers past their window once it
// grows; an ended run's entries go with them.
const PRUNE_AT = 1000
function prune(now) {
if (cache.size < PRUNE_AT) return
for (const [key, entry] of cache) {
if (!entry.pending && now() - entry.at >= CACHE_MS) cache.delete(key)
}
}
/**
* The lines one step's action answers, or null. Never throws.
*/
async function stepLine(step, run, resources, viewer) {
const action = registries.eventAction(step.action_id)
if (!action || typeof action.progress !== 'function') return null
const envelope = {
runId: run.id,
stepId: step.id,
idempotencyKey: step.idempotency_key,
scope: run.scope || '',
params: step.params || {},
// The ledger rows this step made that are still the run's, as the module
// wrote them. Core adds nothing a module did not already hold.
resources: resources.map((r) => ({ kind: r.kind, ref: r.ref, payload: r.payload })),
// Who is reading, as an account id or null. The module decides what its own
// visibility settings let that account see, from its own re-read of the row.
viewer: { userId: viewer.userId == null ? null : viewer.userId },
}
try {
const raw = await withDeadline(() => action.progress(envelope), PROGRESS_BUDGET_MS, action.id)
if (raw && raw.__timedOut) {
log.warn('event progress timed out', { action: action.id, run: run.id, step: step.id })
return null
}
return toLine(raw, action.id)
} catch (err) {
log.warn('event progress threw', { action: action.id, run: run.id, step: step.id, message: err.message })
return null
}
}
/**
* The progress lines for one live run, in step order. Resolves `[]` when there
* is nothing to say or anything went wrong; never rejects.
*
* `viewer.userId` is the reader's account id or null. The cache is keyed on it
* because what a module shows can depend on who is reading.
*/
async function forRun(run, { viewer = { userId: null }, now = Date.now } = {}) {
if (!run || run.id == null) return []
const key = `${run.id}|${viewer.userId == null ? '' : viewer.userId}`
const hit = cache.get(key)
if (hit && hit.lines && now() - hit.at < CACHE_MS) return hit.lines
if (hit && hit.pending) return hit.pending
prune(now)
const pending = (async () => {
let lines = []
try {
const steps = (await stepsDb.listForRun(run.id)).filter((s) => {
const action = registries.eventAction(s.action_id)
return action && typeof action.progress === 'function'
})
if (steps.length) {
const ledger = (await resourcesDb.forRun(run.id)).filter(
(r) => HELD.has(r.status) && r.kind !== resourcesDb.STEP_KIND,
)
const answers = await Promise.all(
steps.map((s) => stepLine(s, run, ledger.filter((r) => String(r.step_id) === String(s.id)), viewer)),
)
lines = answers.filter(Boolean).slice(0, MAX_LINES)
}
} catch (err) {
log.warn('event progress could not be read', { run: run.id, message: err.message })
lines = []
}
cache.set(key, { at: now(), lines })
return lines
})()
cache.set(key, { ...(hit || {}), pending })
try {
return await pending
} finally {
const entry = cache.get(key)
if (entry && entry.pending === pending) delete entry.pending
}
}
/** Test seam. */
function _reset() {
cache.clear()
}
module.exports = { forRun, toLine, PROGRESS_BUDGET_MS, CACHE_MS, MAX_LABEL, MAX_LINES, PRUNE_AT, _reset }

View File

@@ -12,13 +12,14 @@
// one that decides. A spec arriving by any other route (a restore, a fixture, a
// module shipping a definition as content) gets the same answer.
//
// **What this file knows, and what it deliberately refuses.** Two top-level keys
// exist today: `schedule` and `phases`. Unknown top-level keys are REFUSED rather
// **What this file knows, and what it deliberately refuses.** Three top-level
// keys exist today: `schedule`, `starts` and `phases`. Unknown top-level keys are REFUSED rather
// than preserved: a spec that silently carries `announcements` today is a spec
// whose author believes announcements work, and the later phase that gives the
// key meaning would inherit a corpus of unvalidated ones. The refusal list is the
// changelog — Phase 4 added the recurrence shapes, Phase 5 added a phase's
// `advance`, Phase 10 adds `announcements`.
// `advance`, Phase 10 adds `announcements`, and Rust PLAN_REDESIGNS §14.3.12
// added `starts`, the triggers that begin a run (D370).
//
// **Phase 4 widened `schedule` from one shape to four** — `manual`, `once`,
// `weekly`, `monthly` — and every check on them is a check on SHAPE. The
@@ -76,6 +77,24 @@ const MAX_AFTER_SECONDS = 30 * 86_400
// never advances written as one that eventually does.
const MAX_ADVANCE_COUNT = 1000
// A definition's `starts` (Rust PLAN_REDESIGNS §14.3.12, D370): the triggers that
// begin a run of it. Bounded for the reason MAX_PHASES is — a paste guard, not a
// policy, and ten is more than any event here has wanted.
const MAX_STARTS = 10
// How long after one trigger-started run another may start. Thirty minutes by
// default, zero (one run at a time is then the only bound) up to a week. It is
// the same one-integer-one-unit grammar as `after`, for the same proofreading
// reason, and normalised the same way.
const DEFAULT_COOLDOWN = '30m'
const MAX_COOLDOWN_SECONDS = 7 * 86_400
// Core's own lifecycle triggers cannot start a run (D370). `event.run.started`
// starting a run would be a run starting another, and the one-at-a-time rule is
// per definition, so it would not hold a chain of two definitions starting each
// other. Refused by prefix because every one of them is core's and named so.
const CORE_EVENT_PREFIX = 'event.'
// The four closed shapes of §E. `manual` is first because it is the default and
// what an unscheduled draft carries; the other three are recurrences the runner
// expands into occurrences ahead of time.
@@ -323,6 +342,105 @@ function validateAdvance(raw, path, errors) {
return { on: triggerId, where: checked.conditions, count, dormant: false }
}
/**
* Parse a cooldown into seconds, or answer null. `'0m'` (or a bare `0`) is
* allowed here and nowhere else in the duration grammar: no cooldown at all is a
* real choice, and then one run at a time is the only bound.
*/
function parseCooldown(raw) {
if (raw === 0 || raw === '0') return 0
const m = AFTER_RE.exec(String(raw ?? ''))
if (!m) return null
const seconds = Number(m[1]) * AFTER_UNIT_SECONDS[m[2]]
return seconds <= MAX_COOLDOWN_SECONDS ? seconds : null
}
const formatCooldown = (seconds) => (seconds === 0 ? '0m' : formatAfter(seconds))
/**
* Check a definition's `starts` and answer the normalised list (D370).
*
* Each entry is a phase gate's `on` and `where` — the same catalogue, the same
* grammar, the same dormant rule — plus a `cooldown`. A trigger nobody registers
* makes the entry dormant: it saves, and it refuses to publish.
*/
function validateStarts(raw, errors) {
if (raw === undefined || raw === null) return []
if (!Array.isArray(raw)) {
errors.push('spec.starts: expected an array')
return []
}
if (raw.length > MAX_STARTS) {
errors.push(`spec.starts: at most ${MAX_STARTS} triggers`)
return []
}
const out = []
raw.forEach((entry, i) => {
const path = `spec.starts[${i}]`
if (!isPlainObject(entry)) {
errors.push(`${path}: expected an object`)
return
}
const extra = Object.keys(entry).filter((k) => !['on', 'where', 'cooldown', 'dormant'].includes(k))
if (extra.length) {
errors.push(`${path}: unknown key(s) ${extra.join(', ')}`)
return
}
if (typeof entry.on === 'string' && entry.on.startsWith(CORE_EVENT_PREFIX)) {
errors.push(`${path}.on: "${entry.on}" is one of the event system's own triggers, and a run cannot start another`)
return
}
const cooldownSeconds = parseCooldown(entry.cooldown ?? DEFAULT_COOLDOWN)
if (cooldownSeconds === null) {
errors.push(
`${path}.cooldown: expected a duration like "30m" — a whole number of s, m, h or d, ` +
`from 0 to ${formatAfter(MAX_COOLDOWN_SECONDS)}`,
)
return
}
// The trigger and its predicate are a gate's, so a gate's validator answers
// for them: one grammar, one dormant rule, one set of messages.
const gate = validateAdvance({ on: entry.on, where: entry.where ?? null }, path, errors)
if (!gate) return
out.push({ on: gate.on, where: gate.where, cooldown: formatCooldown(cooldownSeconds), dormant: gate.dormant })
})
return out
}
/**
* A `multiple` param's value as the list it is (MODULE_API 1.14.0, Rust
* PLAN_REDESIGNS §12.3).
*
* `{ value: [...] }` or `{ error }`. **A bare value is a list of one**, so a
* spec written by hand or over the API before its author knew the param took
* several does not trip on it. Absent, `null`, `''` and `[]` are all the empty
* list, which the caller reads as unset — `required` means at least one.
*
* Each element is the type's literal, checked by the same `checkLiteral` a
* single value is; an empty string inside the list is refused rather than kept,
* because a blank chip is nothing anyone picked. Duplicates are dropped keeping
* the first, so the order the author picked in is the order the module reads.
*/
function checkList(p, raw) {
if (raw === undefined || raw === null || raw === '') return { value: [] }
const items = Array.isArray(raw) ? raw : [raw]
const out = []
const seen = new Set()
for (let i = 0; i < items.length; i++) {
if (items[i] === '') return { error: `item ${i + 1} is empty` }
const checked = checkLiteral(p.type, items[i])
if (checked.error) return { error: `item ${i + 1} ${checked.error}` }
if (seen.has(checked.value)) continue
seen.add(checked.value)
out.push(checked.value)
}
if (out.length > p.max) return { error: `holds ${out.length} values; the most is ${p.max}` }
return { value: out }
}
/**
* Check one authored param object against an action's declared params.
*
@@ -349,6 +467,14 @@ function checkParams(declaration, raw, path) {
for (const p of declaration.params || []) {
const value = given[p.name]
if (p.multiple) {
const listed = checkList(p, value)
if (listed.error) errors.push(`${path}.params: "${p.name}" ${listed.error}`)
else if (!listed.value.length) {
if (p.required) errors.push(`${path}.params: "${p.name}" is required`)
} else params[p.name] = listed.value
continue
}
if (value === undefined || value === null || value === '') {
if (p.required) errors.push(`${path}.params: "${p.name}" is required`)
continue
@@ -388,7 +514,7 @@ function validate(raw, { knownActionIds = [] } = {}) {
if (!isPlainObject(raw)) return { ok: false, errors: ['spec: expected an object'] }
const allowed = new Set(['schedule', 'phases'])
const allowed = new Set(['schedule', 'phases', 'starts'])
for (const key of Object.keys(raw)) {
if (!allowed.has(key)) {
errors.push(`spec: unknown key "${key}" (Phase 1 understands ${[...allowed].join(', ')})`)
@@ -413,6 +539,9 @@ function validate(raw, { knownActionIds = [] } = {}) {
schedule = validateSchedule(kind, rawSchedule, errors)
}
// ── starts (D370) ──
const starts = validateStarts(raw.starts, errors)
// ── phases ──
const rawPhases = raw.phases
const phases = []
@@ -566,7 +695,10 @@ function validate(raw, { knownActionIds = [] } = {}) {
if (totalSteps > MAX_STEPS) errors.push(`spec: at most ${MAX_STEPS} steps in one definition`)
if (errors.length) return { ok: false, errors }
return { ok: true, spec: { schedule, phases } }
// `starts` is omitted when empty, for the reason a phase's `advance` is: a spec
// carrying `"starts": []` everywhere is a version diff that says every
// definition changed the first time one of them gained a trigger.
return { ok: true, spec: starts.length ? { schedule, starts, phases } : { schedule, phases } }
}
/** Every action id a spec names, dormant ones included. */
@@ -591,6 +723,9 @@ function publishable(spec) {
const dormant = [
...phases.flatMap((p) => (p.steps || []).filter((s) => s.dormant).map((s) => s.actionId)),
...phases.filter((p) => p.advance?.dormant).map((p) => p.advance.on),
// A start on a trigger nothing registers, on the same rule (D370): a version
// that starts on something nobody can emit is one that never starts.
...(spec?.starts || []).filter((s) => s.dormant).map((s) => s.on),
]
return dormant.length ? { ok: false, dormant: [...new Set(dormant)] } : { ok: true, dormant: [] }
}
@@ -603,13 +738,21 @@ const emptySpec = () => ({
module.exports = {
validate,
// An event template's inputs are params, and are checked as one (MODULE_API
// 1.13.0): eventDefinitions.model `buildFromTemplate`.
checkParams,
publishable,
actionIdsIn,
emptySpec,
defaultOnFailure,
parseAfter,
formatAfter,
parseCooldown,
PHASE_KEY,
MAX_STARTS,
DEFAULT_COOLDOWN,
MAX_COOLDOWN_SECONDS,
CORE_EVENT_PREFIX,
SCHEDULE_KINDS,
ADVANCE_KINDS,
MAX_ADVANCE_COUNT,

210
server/src/events/starts.js Normal file
View File

@@ -0,0 +1,210 @@
// ── Starting a run from a trigger: the emit path's third subscriber ────────
//
// Rust PLAN_REDESIGNS §14.3.12 (D370), and EVENTS.md §E "Starting a run from a
// trigger". *"When anyone destroys Bradley on Main, start Launch Site
// Lockdown"*; *"when a champion's boss appears, start Champion's Call"*. Before
// this a trigger could only advance a phase of a run already going (`gates.js`)
// or send a notice (`engine.dispatch`); now a definition's published version may
// carry `starts`, and a firing that matches one creates a run of it, now.
//
// **Same seam and posture as the other two subscribers**: called from
// `engagementEmit.emit`, never awaited, never allowed to reject. Whether some
// event wanted to start is core's business, and a failure of core's must not
// become the module's control flow.
//
// **Four rules decide whether a matching firing starts anything:**
//
// 1. The version must have passed its dry run. A trigger start is unattended,
// as a scheduled one is, and §K's gate falls on the path where nobody is.
// 2. One run at a time per definition. A firing while a run of it is going
// starts nothing and is counted.
// 3. A cooldown after the last trigger-started run (default 30 minutes, 0 to
// 7 days). A firing inside it starts nothing and is counted. Rules 2 and 3
// are what stop twelve road Bradleys dying in a minute starting twelve runs.
// 4. Core's own `event.*` triggers never start a run (refused at save, and
// skipped here as well), so a run starting can never start another.
//
// Rules 2 and 3 are ONE conditional UPDATE (`eventTriggerStarts.db.claim`); the
// occurrence key `UNIQUE (definition_id, scope, scheduled_for)` with
// `scheduled_for` = the firing's time is what makes one firing reported twice
// (two instances ingesting one feed) create one run.
const definitionsDb = require('../model/events/eventDefinitions.db')
const startsDb = require('../model/events/eventTriggerStarts.db')
const runsModel = require('../model/events/eventRuns.model')
const conditions = require('../engagement/conditions')
const registries = require('../modules/registries')
const spec = require('./spec')
const gates = require('./gates')
const log = require('../utils/logger')('event-starts')
// What of a firing's data is kept on the run. The run row is admin-only, and it
// is the answer to "why did this run happen", so the trigger's DECLARED
// variables are kept and nothing else a module happened to send. Bounded, so
// one oversized payload cannot make the insert the thing that fails.
const MAX_ORIGIN_BYTES = 4096
/** The firing's time, in whole seconds (the column's precision), never in the future. */
function firingTime(occurredAt, now) {
const parsed = occurredAt ? new Date(occurredAt) : now
const at = Number.isNaN(parsed.getTime()) || parsed > now ? now : parsed
return new Date(Math.floor(at.getTime() / 1000) * 1000)
}
const sameSecond = (a, b) =>
a && b && Math.floor(new Date(a).getTime() / 1000) === Math.floor(new Date(b).getTime() / 1000)
/** The firing as the run will remember it. */
function originOf(event, declaration, start, at) {
const declared = (declaration?.variables || []).map((v) => v.name)
const data = event.data || {}
let variables = Object.fromEntries(declared.filter((n) => n in data).map((n) => [n, data[n]]))
if (Buffer.byteLength(JSON.stringify(variables), 'utf8') > MAX_ORIGIN_BYTES) {
// Too big to keep whole: keep the ones the start's condition named, which
// are the reason it matched, and say the rest were dropped.
const named = gates.variablesIn(start.where)
variables = Object.fromEntries(named.filter((n) => n in data).map((n) => [n, data[n]]))
variables._truncated = true
}
return {
kind: 'trigger',
triggerId: event.triggerId,
label: declaration?.label || event.triggerId,
occurredAt: at.toISOString(),
subject: event.subject ?? null,
// The start's condition in the builder's own words, so the console can say
// what it matched on without re-reading the version.
matched: gates.phrase(start.where),
variables,
}
}
/**
* Why a firing that matched did not get the claim. A duplicate of the firing
* that started the last run is not counted: it is the same thing happening once,
* reported twice.
*/
async function whyNot(definitionId, at, now) {
const state = await startsDb.forDefinition(definitionId)
if (state && sameSecond(state.last_started_at, at)) return 'duplicate'
if (await startsDb.isGoing(definitionId, now)) return 'running'
// A live claim is another firing starting it this instant: the run is going in
// every sense but the row.
if (state?.claimed_at && now - new Date(state.claimed_at) < startsDb.CLAIM_STALE_MS) return 'running'
return 'cooldown'
}
/** One definition, one firing. Answers what happened, for the summary and the tests. */
async function consider(definition, event, at, now) {
const starts = (definition.version_spec?.starts || []).filter((s) => s.on === event.triggerId && !s.dormant)
const start = starts.find((s) => conditions.evaluate(s.where, event.data || {}))
if (!start) return 'unmatched'
if (now - at > Number(definition.grace_seconds || 0) * 1000) {
// A firing older than the grace window would make a run the missed sweep
// takes on its next tick. Said, and not started.
log.warn('a firing too old to start a run', { definition: definition.id, trigger: event.triggerId, at })
return 'stale'
}
if (!definition.version_verified_at) {
await startsDb.ignore(definition.id, 'unverified', now)
log.warn('trigger start held: the published version has never been verified', {
definition: definition.id,
title: definition.title,
trigger: event.triggerId,
})
return 'unverified'
}
const cooldownSeconds = spec.parseCooldown(start.cooldown ?? spec.DEFAULT_COOLDOWN) ?? 0
if (!(await startsDb.claim(definition.id, { at, cooldownSeconds, now }))) {
const reason = await whyNot(definition.id, at, now)
if (reason !== 'duplicate') await startsDb.ignore(definition.id, reason, now)
return reason
}
const declaration = registries.eventTrigger(event.triggerId)
let result
try {
result = await runsModel.create(
definition.id,
// Scope is empty, as a scheduled occurrence's is (org lead, 2026-09-02): a
// scope registry does not exist, and the condition is what narrows a start
// to one server.
{ scope: '', scheduledFor: at, source: 'trigger', origin: originOf(event, declaration, start, at) },
null,
)
} catch (err) {
await startsDb.release(definition.id)
throw err
}
if (!result.ok) {
await startsDb.release(definition.id)
if (result.code === 'unverified') await startsDb.ignore(definition.id, 'unverified', now)
log.warn('trigger start refused', { definition: definition.id, errors: result.errors })
return 'refused'
}
if (!result.created) {
// The occurrence already existed: this firing was reported twice, and the
// claimant that made the run has recorded it. Nothing to count.
await startsDb.release(definition.id)
return 'duplicate'
}
await startsDb.started(definition.id, { at, runId: result.run.id })
log.info('run started by a trigger', { definition: definition.id, run: result.run.id, trigger: event.triggerId })
return 'started'
}
/**
* The trigger stream's third subscriber.
*
* The common answer is one indexed-by-nothing query over the ready definitions
* returning no rows: a deployment has tens of definitions, not thousands, and a
* JSON column cannot carry an index. If that ever changes, a side table of
* (trigger, definition) written at publish is the fix.
*/
async function observe(event, { now = new Date() } = {}) {
const summary = { definitions: 0, started: 0, ignored: 0 }
try {
if (!event?.triggerId || event.triggerId.startsWith(spec.CORE_EVENT_PREFIX)) return summary
const candidates = await definitionsDb.findStartingOn(event.triggerId)
summary.definitions = candidates.length
if (!candidates.length) return summary
const at = firingTime(event.occurredAt, now)
for (const definition of candidates) {
try {
const outcome = await consider(definition, event, at, now)
if (outcome === 'started') summary.started += 1
if (['running', 'cooldown', 'unverified'].includes(outcome)) summary.ignored += 1
} catch (err) {
log.error('trigger start failed', { definition: definition.id, trigger: event.triggerId, message: err.message })
}
}
} catch (err) {
log.error('trigger start observation failed', { trigger: event?.triggerId, message: err.message })
}
return summary
}
/**
* The editor's line about a definition's trigger starts, from the state row.
* Null when no trigger has ever tried to start it.
*/
function describeState(row) {
if (!row) return null
return {
lastStartedAt: row.last_started_at || null,
lastRunId: row.last_run_id || null,
ignoredRunning: Number(row.ignored_running || 0),
ignoredCooldown: Number(row.ignored_cooldown || 0),
ignoredUnverified: Number(row.ignored_unverified || 0),
lastIgnoredAt: row.last_ignored_at || null,
lastIgnoredReason: row.last_ignored_reason || null,
}
}
module.exports = { observe, consider, describeState, firingTime, originOf, MAX_ORIGIN_BYTES }

View File

@@ -159,6 +159,30 @@ const findSchedulable = async ({ listedOnly = false } = {}) => {
return rows.map((row) => ({ ...row, version_spec: parseJson(row.version_spec, null) }))
}
/**
* Every `ready` definition whose PUBLISHED version starts on this trigger
* (Rust PLAN_REDESIGNS §14.3.12, D370). The emit path's question, asked on every
* firing, so it answers in one query and the common answer is no rows.
*
* Read from the version, never the working copy, for the reason the schedule
* expansion is: a start an author is midway through typing must not fire.
* `JSON_EXTRACT` over `$.starts[*].on` is an array, or NULL for a version with
* no starts, and `JSON_CONTAINS` of NULL is not true.
*/
const findStartingOn = async (triggerId) => {
const rows = await query(
`SELECT d.id, d.title, d.grace_seconds, d.current_version_id,
v.spec AS version_spec, v.verified_at AS version_verified_at
FROM event_definitions d
JOIN event_versions v ON v.id = d.current_version_id
WHERE d.state = 'ready'
AND JSON_CONTAINS(JSON_EXTRACT(v.spec, '$.starts[*].on'), JSON_QUOTE(?))
ORDER BY d.id`,
[triggerId],
)
return rows.map((row) => ({ ...row, version_spec: parseJson(row.version_spec, null) }))
}
/**
* One definition by slug, for the PUBLIC event page (Phase 14a).
*
@@ -206,6 +230,7 @@ module.exports = {
listPublicBySeries,
slugTaken,
findSchedulable,
findStartingOn,
insert,
update,
markReady,

View File

@@ -31,6 +31,7 @@ const verifier = require('../../events/verify')
const registries = require('../../modules/registries')
const { slugify, uniqueSlug } = require('../teams/teamSlug')
const { cleanBody } = require('../../utils/sanitizeHtml')
const log = require('../../utils/logger')('events')
const MAX_TITLE = 200
const MAX_SUMMARY = 500
@@ -399,9 +400,111 @@ async function verify(id, user) {
}
}
// How long a template's `build()` may take. It may read the module's own data or
// ask a sidecar, and an author is waiting on the other side of the click.
const TEMPLATE_BUILD_MS = 10_000
/**
* Fill an event template in (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2.5, D192).
*
* `{ ok: true, draft: { title, summary, spec } }`, or `{ ok: false, status,
* errors }`. **Nothing is saved.** The draft goes back to the editor, which opens
* it like any new event; the author saves it through `create()` and its rules,
* so a template cannot make a definition the save path would refuse.
*
* The module is not trusted at either end. The inputs are checked against the
* template's declaration before `build()` sees them, and what `build()` returns
* is validated as a spec after. A `build()` that refuses says why in
* `{ ok: false, error }` — the author's sentence — and one that throws or hangs
* is logged and answered with a sentence of core's, because a stack trace is
* not something to put on an author's screen.
*/
async function buildFromTemplate(templateId, rawInputs) {
const template = registries.eventTemplate(String(templateId || ''))
if (!template) {
return { ok: false, status: 404, errors: [`no module registers the event template "${templateId}"`] }
}
const checked = spec.checkParams({ id: template.id, params: template.inputs }, rawInputs, 'inputs')
if (checked.errors.length) {
return { ok: false, status: 400, errors: checked.errors.map((e) => e.replace(/^inputs\.params: /, '')) }
}
let built
let timer
try {
built = await Promise.race([
Promise.resolve(template.build({ inputs: checked.params })),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`build() took longer than ${TEMPLATE_BUILD_MS} ms`)), TEMPLATE_BUILD_MS)
}),
])
} catch (err) {
log.error('event template build failed', { template: template.id, owner: template.owner, message: err.message })
return { ok: false, status: 502, errors: [`"${template.label}" could not be filled in — the module that provides it failed`] }
} finally {
clearTimeout(timer)
}
if (!built || typeof built !== 'object') {
return { ok: false, status: 502, errors: [`"${template.label}" answered with no draft`] }
}
if (built.ok === false) {
return { ok: false, status: 400, errors: [String(built.error || `"${template.label}" refused those inputs`)] }
}
const checkedSpec = spec.validate(built.spec)
if (!checkedSpec.ok) {
// The module's mistake, not the author's, and named as such: the author
// cannot fix a template by retyping its inputs.
log.error('event template built an invalid spec', { template: template.id, errors: checkedSpec.errors })
return {
ok: false,
status: 502,
errors: [`"${template.label}" made a plan core cannot accept`, ...checkedSpec.errors],
}
}
return {
ok: true,
draft: {
title: String(built.title || template.label).slice(0, MAX_TITLE),
summary: built.summary ? String(built.summary).slice(0, MAX_SUMMARY) : null,
spec: checkedSpec.spec,
},
}
}
/**
* Does the working copy differ from the published version? (Rust PLAN_REDESIGNS
* §2.3, U-5.)
*
* A run is pinned to the PUBLISHED version, so an author who edited, saved and
* pressed Start ran the old plan without being told. The editor asks only when
* this is true. Compared as data, keys sorted, because the two are stored as
* JSON by different writes and a key order is not an edit. A definition never
* published has nothing to be ahead of, and answers false.
*/
async function draftAhead(row) {
if (!row || !row.current_version_id) return false
const version = await versionsDb.getById(row.current_version_id)
if (!version) return false
return stableJson(row.spec) !== stableJson(version.spec)
}
function stableJson(value) {
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`
if (value && typeof value === 'object') {
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableJson(value[k])}`).join(',')}}`
}
return JSON.stringify(value === undefined ? null : value)
}
module.exports = {
validate,
create,
buildFromTemplate,
draftAhead,
save,
publish,
archive,

View File

@@ -36,6 +36,7 @@ const versionsDb = require('./eventVersions.db')
const participantsDb = require('./eventRunParticipants.db')
const calendarModel = require('./eventCalendar.model')
const recurrence = require('../../events/recurrence')
const progress = require('../../events/progress')
// The public calendar's window when a caller names neither end: a few days BACK
// through a month out. A visitor arriving at /site/events wants "what is on", and
@@ -91,21 +92,36 @@ const isLive = (status) => publicStatus(status) === 'live'
/**
* The label of the phase a run is in, resolved from the PINNED version's spec.
*
* A phase id is a slug an author typed and the label is what they meant it to
* read as, so a page rendering the id would show `phase-2` to the public. A
* A phase key is a slug an author typed and the label is what they meant it to
* read as, so a page rendering the key would show `phase-2` to the public. A
* phase the spec does not name answers null and the page shows nothing, which is
* the right answer for a version edited since: the run pinned the old spec and
* the old spec is what it is executing.
*
* **A run's `current_phase` is the phase's `key`**, which is what `spec.js`
* validates and the engine writes. This matched `id` until RunicNPC stage 9
* (D314), so every live run read "Under way" since Events Phase 14a; `id` is
* still accepted second, for a spec stored in that older shape.
*/
function phaseLabel(spec, phaseId) {
if (!phaseId || !spec || !Array.isArray(spec.phases)) return null
const phase = spec.phases.find((p) => p && p.id === phaseId)
return (phase && (phase.label || phase.id)) || null
function phaseLabel(spec, phaseKey) {
if (!phaseKey || !spec || !Array.isArray(spec.phases)) return null
const phase =
spec.phases.find((p) => p && p.key === phaseKey) || spec.phases.find((p) => p && p.id === phaseKey)
return (phase && (phase.label || phase.key || phase.id)) || null
}
/** One calendar entry, from a materialised run. */
/**
* One calendar entry, from a materialised run.
*
* **`runId` is published because the event page already publishes it** on every
* occurrence, and `?run=` takes it. The calendar was the one public shape that
* named a run without saying which, so a client holding a run id from elsewhere
* (a module's map marker) had no way to find its event but to fetch every event
* page. A projection has none: nothing is committed to it.
*/
const publicRunEntry = (run) => ({
kind: 'run',
runId: run.id,
title: run.definition_title,
slug: run.definition_slug,
seriesName: run.series_name || null,
@@ -280,7 +296,7 @@ const publicOccurrence = (run, spec) => ({
* turn a stale link in a months-old mail into a dead end rather than a page
* about the thing the mail was about.
*/
async function event(slug, { runId = null } = {}) {
async function event(slug, { runId = null, userId = null } = {}) {
const definition = await definitionsDb.getPublicBySlug(String(slug || ''))
if (!definition) return { ok: false, status: 404, errors: ['Not found'] }
@@ -330,6 +346,13 @@ async function event(slug, { runId = null } = {}) {
const specRun = named || live[0] || null
const spec = specRun ? (await versionsDb.getById(specRun.version_id))?.spec || null : null
// How the live occurrence stands, in the words its steps' modules chose
// (MODULE_API 1.12.0). Only for a live run: a finished one has results, and a
// scheduled one has nothing to count yet. `progress.forRun` never rejects and
// answers `[]` when nobody has anything to say.
const current = live[0] ? publicOccurrence(live[0], spec) : null
if (current) current.progress = await progress.forRun(live[0], { viewer: { userId } })
return {
ok: true,
status: 200,
@@ -342,7 +365,7 @@ async function event(slug, { runId = null } = {}) {
timezone: definition.timezone,
series: series ? { name: series.name, slug: series.slug } : null,
live: live.length > 0,
current: live[0] ? publicOccurrence(live[0], spec) : null,
current,
next: next ? publicOccurrence(next, spec) : null,
upcoming: upcoming.map((r) => publicOccurrence(r, spec)),
past: past.map((r) => publicOccurrence(r, spec)),

View File

@@ -53,6 +53,9 @@ const KINDS = [
// question is about the world.
'resource.recorded', // a step reported what it created or borrowed, and it is ledgered
'resource.orphaned', // a module reports a ledgered resource is no longer in force
// MODULE_API 1.11.0's one (Rust PLAN_FIXES D183): the game ended a resource at
// its own deadline, which is the plan working rather than something vanishing.
'resource.expired', // a module reports the game ended a ledgered resource by itself
'cleanup.reverted', // a group of resources came back
'cleanup.failed', // a group did not, with the reason and how it was left
'cleanup.swept', // one pass over a run's ledger, and what it found

View File

@@ -327,6 +327,42 @@ async function markOrphaned(id, detail = null) {
)
}
/**
* The rows one module holds for one target that the game may have let go of on
* its own — what `ctx.events.expired` looks for (MODULE_API 1.11.0).
*
* `orphaned` is included on purpose: a reconcile that ran before the module heard
* the expiry filed the row as vanished, and the expiry is the better answer.
* `reverting` is not: a revert already in flight finds the thing gone, which §L
* calls a success, and it settles as `reverted` on its own.
*/
async function expirableByTarget(owner, kind, ref) {
const rows = await query(
`SELECT ${COLUMNS} FROM event_run_resources
WHERE owner_module = ? AND kind = ? AND ref = ?
AND status IN ('pending', 'confirmed', 'orphaned')
ORDER BY id`,
[owner, kind, ref],
)
return rows.map(hydrate)
}
/**
* The game ended it by itself, as it was told to — a zone reaching its deadline.
* Terminal like `reverted`, so teardown never tries to give it back, and unlike
* `orphaned`, which is a thing that vanished with nobody asking. Guarded on the
* status so a row a revert has just claimed is left to that revert.
*/
async function markExpired(id, detail = null) {
const result = await query(
`UPDATE event_run_resources
SET status = 'expired', last_error = ?
WHERE id = ? AND status IN ('pending', 'confirmed', 'orphaned')`,
[detail === null ? null : String(detail).slice(0, 500), id],
)
return (result.affectedRows || 0) > 0
}
/**
* Terminal runs that still owe the world something — the cleanup leg's scan.
*
@@ -366,8 +402,30 @@ async function runsNeedingCleanup(limit = 25, maxAttempts = 3) {
)
}
/**
* Finished runs still marked `pending` that have no unresolved row at all — a
* run whose last resource the game expired while it was still going (MODULE_API
* 1.11.0). The sweep settles them `complete`; `runsNeedingCleanup` cannot see
* them because it joins on an unresolved row.
*/
async function finishedRunsWithNothingLeft(limit = 25) {
const rows = await query(
`SELECT r.id FROM event_runs r
WHERE r.status IN ('completed', 'cancelled', 'failed', 'missed')
AND r.cleanup_status = 'pending'
AND NOT EXISTS (
SELECT 1 FROM event_run_resources res
WHERE res.run_id = r.id AND res.status IN (?, ?, ?, ?, ?))
ORDER BY r.id
LIMIT ?`,
[...UNRESOLVED, Number(limit)],
)
return rows.map((row) => Number(row.id))
}
module.exports = {
STEP_KIND,
finishedRunsWithNothingLeft,
HELD,
UNRESOLVED,
reserve,
@@ -385,5 +443,7 @@ module.exports = {
liveForModule,
modulesWithLiveRows,
markOrphaned,
expirableByTarget,
markExpired,
runsNeedingCleanup,
}

View File

@@ -15,7 +15,13 @@
const { query } = require('../../utils/db')
const { parseJson } = require('./eventJson')
const hydrate = (row) => row && { ...row, params: parseJson(row.params, null), rehearsal: Boolean(row.rehearsal) }
const hydrate = (row) =>
row && {
...row,
params: parseJson(row.params, null),
origin: parseJson(row.origin, null),
rehearsal: Boolean(row.rehearsal),
}
// The statuses a run never leaves. A transition INTO one of these stamps
// `ended_at` and drops the claim, and only rows in one of them are eligible for
@@ -90,8 +96,8 @@ const materialise = async (run) => {
const result = await query(
`INSERT IGNORE INTO event_runs
(definition_id, version_id, scope, scheduled_for, timezone, concurrency_key,
params, rehearsal, started_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
params, rehearsal, started_by, origin)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
run.definition_id,
run.version_id,
@@ -102,6 +108,8 @@ const materialise = async (run) => {
run.params === null || run.params === undefined ? null : JSON.stringify(run.params),
run.rehearsal ? 1 : 0,
run.started_by,
// Why the run exists when a trigger started it (D370); NULL otherwise.
run.origin ? JSON.stringify(run.origin) : null,
],
)
return Number(result?.affectedRows || 0) === 1 ? result.insertId : null

View File

@@ -69,7 +69,7 @@ function renderConcurrencyKey(template, params) {
*/
async function create(
definitionId,
{ scope = '', scheduledFor = null, rehearsal = false, params = null, source = 'manual' } = {},
{ scope = '', scheduledFor = null, rehearsal = false, params = null, source = 'manual', origin = null } = {},
userId,
) {
const definition = await definitionsDb.getById(definitionId)
@@ -97,7 +97,10 @@ async function create(
// nobody is. A version is immutable, so a dry run that passed against it stays
// true, which is what makes the pass a property of the version rather than
// something re-earned every occurrence.
if (source === 'schedule' && !version.verified_at) {
//
// **A trigger start is unattended too** (D370): a boss dying at four in the
// morning starts the run with nobody watching, exactly as a schedule does.
if ((source === 'schedule' || source === 'trigger') && !version.verified_at) {
return {
ok: false,
status: 409,
@@ -124,6 +127,7 @@ async function create(
params,
rehearsal,
started_by: userId,
origin,
})
if (runId === null) {
@@ -146,8 +150,11 @@ async function create(
// a recurrence (Phase 4). Both produce the same row, and the log is the
// only place the difference is recorded — `started_by` is NULL for both a
// scheduled occurrence and one started by a since-deleted account.
// 'trigger' is a game firing (D370), and it is the one source that also
// says WHAT: the origin goes into the audit line as well as on the row.
source,
by: userId,
...(origin ? { origin } : {}),
},
})

View File

@@ -0,0 +1,106 @@
// ── event_trigger_starts — SQL only ────────────────────────────────────────
//
// Rust PLAN_REDESIGNS §14.3.12 (D370), and EVENTS.md §E "Starting a run from a
// trigger". One row per definition a trigger has tried to start. `events/starts.js`
// decides; this file holds the claim and the counts.
//
// **The claim is one statement with every rule inside it.** A firing may start a
// run only when no claim is live, the last trigger-started run is out of its
// cooldown, and no run of the definition is going. Read-then-write would let two
// firings arriving together each see a quiet definition and both start, which is
// exactly the twelve-Bradleys case the rule exists for.
const { query } = require('../../utils/db')
// A claim older than this belongs to a process that died between the claim and
// the run row existing. A minute is far longer than an insert takes.
const CLAIM_STALE_MS = 60_000
// What "a run is going" means for the one-at-a-time rule: started and not ended,
// or scheduled and already due — a trigger-started run is `scheduled` for up to
// one tick before the runner claims it, and it is going from the moment it exists.
const GOING_SQL = `
SELECT 1 FROM event_runs r
WHERE r.definition_id = t.definition_id
AND (r.status IN ('starting','running','paused','ending')
OR (r.status = 'scheduled' AND r.scheduled_for <= ?))`
const REASONS = ['running', 'cooldown', 'unverified']
/** The row, or null when no trigger has ever tried to start this definition. */
const forDefinition = async (definitionId) => {
const [row] = await query('SELECT * FROM event_trigger_starts WHERE definition_id = ?', [definitionId])
return row || null
}
/**
* Try to own the start. `true` when this caller may create the run.
*
* `at` is the firing's time (whole seconds), `cooldownSeconds` the matching
* start's own. The row is made first with `INSERT IGNORE`, so the UPDATE always
* has something to guard.
*/
async function claim(definitionId, { at, cooldownSeconds, now }) {
await query('INSERT IGNORE INTO event_trigger_starts (definition_id) VALUES (?)', [definitionId])
const result = await query(
`UPDATE event_trigger_starts t
SET t.claimed_at = ?
WHERE t.definition_id = ?
AND (t.claimed_at IS NULL OR t.claimed_at < ?)
AND (t.last_started_at IS NULL OR t.last_started_at <= ?)
AND NOT EXISTS (${GOING_SQL})`,
[
now,
definitionId,
new Date(now.getTime() - CLAIM_STALE_MS),
new Date(at.getTime() - cooldownSeconds * 1000),
now,
],
)
return Number(result?.affectedRows || 0) === 1
}
/** The run exists: record it, drop the claim, and start the counts again. */
const started = (definitionId, { at, runId }) =>
query(
`UPDATE event_trigger_starts
SET claimed_at = NULL, last_started_at = ?, last_run_id = ?,
ignored_running = 0, ignored_cooldown = 0, ignored_unverified = 0,
last_ignored_at = NULL, last_ignored_reason = NULL
WHERE definition_id = ?`,
[at, runId, definitionId],
)
/** The claim came to nothing (the create refused): give it back. */
const release = (definitionId) =>
query('UPDATE event_trigger_starts SET claimed_at = NULL WHERE definition_id = ?', [definitionId])
/**
* Count a firing that started nothing, by why. `reason` is one of REASONS and
* names its own column, so it is checked against the list before it reaches SQL.
*/
async function ignore(definitionId, reason, now) {
if (!REASONS.includes(reason)) throw new Error(`unknown ignore reason "${reason}"`)
await query('INSERT IGNORE INTO event_trigger_starts (definition_id) VALUES (?)', [definitionId])
await query(
`UPDATE event_trigger_starts
SET ignored_${reason} = ignored_${reason} + 1, last_ignored_at = ?, last_ignored_reason = ?
WHERE definition_id = ?`,
[now, reason, definitionId],
)
}
/** Is a run of this definition going right now? The ignore path's "why". */
const isGoing = async (definitionId, now) => {
const rows = await query(
`SELECT 1 FROM event_runs r
WHERE r.definition_id = ?
AND (r.status IN ('starting','running','paused','ending')
OR (r.status = 'scheduled' AND r.scheduled_for <= ?))
LIMIT 1`,
[definitionId, now],
)
return rows.length > 0
}
module.exports = { forDefinition, claim, started, release, ignore, isGoing, REASONS, CLAIM_STALE_MS }

View File

@@ -17,6 +17,11 @@
// through modules/install.js, the same fetch-verify-unpack path the admin panel
// uses, under the same host allowlist.
//
// **A site runs one module** (org lead, 2026-09-23), and install.js enforces it
// for this path too: a declaration naming a second module installs the first,
// and the second is refused — logged and kept for the admin screen like any
// other failed entry, never fatal to the boot.
//
// Three things this file deliberately does not do:
//
// - **It does not decide whether a module RUNS.** Resolution owns what is on

View File

@@ -290,6 +290,28 @@ function isInstalled(id) {
}
}
/**
* Every module on the volume, by id — the directories the loader would scan.
*
* The loader's own rule, restated: a directory whose name is a module id and
* which holds a `module.json`. That excludes an install's scratch directory
* (`.install-*`) and a swap's aside copy (`<id>.replaced-*`), neither of which
* is a module and both of which can briefly exist beside one.
*/
function installedIds() {
let entries
try {
entries = fs.readdirSync(loader.dir(), { withFileTypes: true })
} catch {
return [] // no modules directory is the normal case for a bare core
}
return entries
.filter((e) => e.isDirectory() && ID.test(e.name))
.filter((e) => fs.existsSync(path.join(loader.dir(), e.name, 'module.json')))
.map((e) => e.name)
.sort()
}
/**
* The absolute path of a module's `purge.sql`, or null.
*
@@ -348,6 +370,25 @@ async function install({ url, hosts, expect = null, fetchImpl = fetch }) {
)
}
// One module per site (org lead, 2026-09-23). A site is one game, and the
// contract has singletons that assume it: `registerTeamProvider` holds ONE
// value per deployment, and a second module registering one fails its whole
// load — with modules loaded alphabetically, installing `rust` beside `uo`
// would have taken `uo` down, not `rust`. So an install is an UPGRADE of the
// module already here, or it is refused before a byte is downloaded.
//
// Refused here rather than in the admin controller so the declared module set
// (modules/declared.js) gets the same answer: an environment naming two
// modules installs the first and is told why the second was not.
const others = installedIds().filter((id) => id !== manifest.id)
if (others.length) {
throw new InstallError(
`this site already runs the module "${others.join('", "')}", and a site runs one module. ` +
`Upgrade it with its own release, or remove it before installing "${manifest.id}".`,
{ status: 409 },
)
}
const target = moduleDir(manifest.id)
const scratch = await fsp.mkdtemp(path.join(loader.dir(), `.install-${manifest.id}-`))
const tarball = path.join(scratch, 'bundle.tar.gz')
@@ -444,6 +485,7 @@ module.exports = {
removeDir,
moduleDir,
isInstalled,
installedIds,
purgeFile,
MAX_MANIFEST_BYTES,
MAX_ARTIFACT_BYTES,

View File

@@ -261,6 +261,27 @@ function buildCtx(id, moduleRoot) {
(err) => { log.error('ctx.events.reconcile failed', { module: id, message: err.message }) },
)
},
// MODULE_API 1.11.0 (Rust PLAN_FIXES D183). The game ended one of this
// module's ledgered resources at its own deadline — a Rust zone erased when
// its time was up. Recorded as `expired`: terminal, never given back, and a
// different sentence on the console from `orphaned`, which is reconcile's
// word for a thing that vanished with nobody asking.
//
// `id` bound, fire-and-forget and returns undefined, all three for
// `reconcile`'s reasons directly above. A `{ kind, ref }` that names no
// live row is not an error: a module hears expiries of things no run ever
// ledgered, and telling it so would be noise it can do nothing with.
expired: (resource) => {
// eslint-disable-next-line global-require
require('../events/cleanup')
.expireResource(id, resource || {})
.then(
(summary) => {
if (summary && summary.expired) log.info('event resource expired', { module: id, ...summary })
},
(err) => { log.error('ctx.events.expired failed', { module: id, message: err.message }) },
)
},
},
// The in-app sink (§5.1) — a module writing the inbox directly, without a
// rule. Live from Phase 7; it threw until the `user_notifications` table
@@ -438,6 +459,13 @@ function buildApi(record) {
once('registerEventOptionSources')
record.staged.registerEventOptionSources(sources)
},
// API 1.13.0. A named starting point for a new event (Rust PLAN_REDESIGNS
// §2.5): inputs in, an ordinary draft out. Its own id space, like the four
// above, and `once` for the same reason.
registerEventTemplates(templates) {
once('registerEventTemplates')
record.staged.registerEventTemplates(templates)
},
// The two lifecycle hooks (§2.5). Registered here, dispatched from
// lifecycle.js — this file runs with no database and the hooks run with one.
// Both are optional: a module with no warm-up and nothing to close simply

View File

@@ -176,6 +176,16 @@ const eventLeases = new Map()
// is worse than the typo the dropdown existed to prevent.
const eventOptionSources = new Map()
// template id → { owner, id, label, description, inputs, build } (MODULE_API
// 1.13.0; Rust PLAN_REDESIGNS §2.5, D192).
//
// **An authoring shortcut and nothing else.** A template turns a handful of
// inputs into an ordinary draft — phases, steps, params — and the draft is the
// only thing that survives: no column records which template made it, and the
// runner never sees one. That is what lets a template change, or its module go,
// without touching a single definition it was ever used for.
const eventTemplates = new Map()
// owner → { templates: [...], ruleGroups: [...] } (ENGAGEMENT.md Phase 11b,
// decision 7). What a module ships as CONTENT rather than as contract: the
// bodies its triggers render through, and the rules an operator switches on.
@@ -435,14 +445,14 @@ async function resolveAudience(id, params = {}) {
/**
* Every declaration WITHOUT its callables — what the admin catalog serves.
*
* `perform`, `revert`, `reconcile` and `cost` are stripped for the same reason `resolve` is
* `perform`, `revert`, `reconcile`, `cost` and `progress` are stripped for the same reason `resolve` is
* stripped from an audience and `handler` from a slash command: this is the
* object that leaves the process, and the browser's whole relationship with an
* action is naming one by id. §F's "a module registers actions server-side and
* adds no routes for them" is only true if the functions never ride out.
*/
const allEventActions = () =>
[...eventActions.values()].map(({ perform, revert, reconcile, cost, ...rest }) => rest)
[...eventActions.values()].map(({ perform, revert, reconcile, cost, progress, ...rest }) => rest)
/** One declaration, callables included. The runner's lookup (Phase 2). */
const eventAction = (id) => eventActions.get(id) || null
@@ -531,6 +541,9 @@ const allEventOptionSources = () =>
// still answers something, where refusing would blank a form mid-keystroke.
const MAX_OPTION_QUERY = 120
// The longest note an option may carry, in characters.
const MAX_OPTION_NOTE = 300
/**
* Resolve one option source, or say why not. Never throws.
*
@@ -584,6 +597,12 @@ async function resolveOptionSource(id, { q = '' } = {}) {
if (o.value === undefined || o.value === null || o.value === '') continue
const option = { value: String(o.value), label: String(o.label ?? o.value) }
if (o.group) option.group = String(o.group)
// A sentence the editor shows under the field while this option is the
// chosen one (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2.6) — advice about
// the value, like "9 of 41 linked players have used this kit up". Bounded,
// because it is rendered as-is and one option's essay is a form nobody
// can read.
if (o.note) option.note = String(o.note).slice(0, MAX_OPTION_NOTE)
options.push(option)
}
// `searchable` is reported so the authoring form knows which field is a
@@ -1005,9 +1024,30 @@ const DEFAULT_BUDGET_MS = 10_000
// and Phase 2's lease has to be longer than this to mean anything.
const MAX_BUDGET_MS = 3_600_000
function checkActionParam(actionId, entry, seen) {
const { name, type, required, example, description, source } = entry || {}
const where = `registerEventActions: ${actionId}`
// A param that is a length of time says which unit it is in (MODULE_API 1.13.0;
// Rust PLAN_REDESIGNS §2.2). One unit, minutes, because every timed param
// registered so far is one — a lease's `minutes`, a zone's `minutes` — and a
// vocabulary of one is a vocabulary that can grow without a version.
const PARAM_DURATIONS = ['minutes']
// A param that holds several values (MODULE_API 1.14.0; Rust PLAN_REDESIGNS
// §12.3, D344). Two types, because the one step that needed it picks strings
// from a source and an int list is the same check one type over; a list of
// booleans, dates or links is a shape nothing has asked for, and every control
// the editor draws for a list is a picker or a tag box.
const MULTIPLE_PARAM_TYPES = ['string', 'int']
// `max` when the declaration leaves it out, and the most it may say. The ceiling
// is a bound on one step's params, not a number anyone should reach: a list of a
// hundred is a step nobody can read back.
const DEFAULT_MULTIPLE_MAX = 20
const MAX_MULTIPLE_MAX = 100
// `call` names the registration in the error, because a template's inputs are
// checked by this same function (they ARE params: one control each, with a
// name, a type, an example and maybe a source).
function checkActionParam(actionId, entry, seen, call = 'registerEventActions') {
const { name, type, required, example, description, source, duration, multiple, max } = entry || {}
const where = `${call}: ${actionId}`
if (!PARAM_NAME.test(name || '')) throw new Error(`${where}: bad param name "${name}"`)
if (seen.has(name)) throw new Error(`${where}: param "${name}" declared twice`)
seen.add(name)
@@ -1030,6 +1070,49 @@ function checkActionParam(actionId, entry, seen) {
if (source !== undefined && !ACTION_ID.test(source || '')) {
throw new Error(`${where}: param "${name}" has a bad option source "${source}"`)
}
// **A duration is what lets the editor see a timed step** (§2.2). A phase that
// ends before its longest timed step gives the thing back early — a lease held
// "for 10 minutes" in a phase that ends at once lasted one second — and the
// editor can only say so about a param that says it is a length of time.
// Numeric only: a duration typed as a string would be a number the editor
// has to parse with rules nobody declared.
if (duration !== undefined && duration !== null) {
if (!PARAM_DURATIONS.includes(duration)) {
throw new Error(`${where}: param "${name}" has duration "${duration}"; the one unit is ${PARAM_DURATIONS.join(', ')}`)
}
if (type !== 'int' && type !== 'float') {
throw new Error(`${where}: param "${name}" is a duration and must be int or float, not ${type}`)
}
}
// **`multiple` makes the value a list** (1.14.0, §12.3). The example stays ONE
// value — it is the placeholder of the box a value is typed into — and the
// value a step stores is a JSON array of them (`events/spec.js`).
//
// Refused on a duration, because a list of lengths of time is not a hold the
// editor can keep a phase open for, and on a template's inputs, because
// `build()` is a module's own code reading `inputs.x` as one value and this
// version does not change what it is handed.
if (multiple !== undefined && multiple !== null && multiple !== false) {
if (multiple !== true) throw new Error(`${where}: param "${name}" multiple must be true or left out`)
if (call === 'registerEventTemplates') {
throw new Error(`${where}: input "${name}" cannot be multiple; a template's inputs are single values`)
}
if (!MULTIPLE_PARAM_TYPES.includes(type)) {
throw new Error(`${where}: param "${name}" is multiple and must be ${MULTIPLE_PARAM_TYPES.join(' or ')}, not ${type}`)
}
if (duration !== undefined && duration !== null) {
throw new Error(`${where}: param "${name}" cannot be both multiple and a duration`)
}
if (Array.isArray(example)) {
throw new Error(`${where}: param "${name}" needs ONE example, not a list (it is the placeholder of one value)`)
}
}
if (max !== undefined && max !== null) {
if (multiple !== true) throw new Error(`${where}: param "${name}" has a max but is not multiple`)
if (!Number.isInteger(max) || max < 1 || max > MAX_MULTIPLE_MAX) {
throw new Error(`${where}: param "${name}" max must be 1..${MAX_MULTIPLE_MAX}, got "${max}"`)
}
}
return {
name,
type,
@@ -1037,11 +1120,15 @@ function checkActionParam(actionId, entry, seen) {
example,
source: source === undefined ? null : source,
description: description || '',
...(duration ? { duration } : {}),
// Absent rather than `false` on every other param, as `duration` is, so a
// module that never says it reads back exactly the declaration it wrote.
...(multiple === true ? { multiple: true, max: max ?? DEFAULT_MULTIPLE_MAX } : {}),
}
}
/**
* `registerEventActions([{ id, label, risk, reversible, version, budgetMs, cost, params, perform, revert, reconcile }])`.
* `registerEventActions([{ id, label, risk, reversible, version, budgetMs, cost, params, perform, revert, reconcile, progress }])`.
*
* A typed verb core may ask a registrant to carry out. Everything decidable from
* the argument alone is decided here, at the call; the collision — is this id
@@ -1118,6 +1205,12 @@ function checkEventActionShape(entry) {
if (a.cost !== undefined && typeof a.cost !== 'function') {
throw new Error(`registerEventActions: ${a.id} cost must be a function of its params`)
}
// 1.12.0, optional: how a live run's step stands, for its public page
// (`events/progress.js`). Any action may declare it; an action that ledgers
// nothing can still say something about the world it changed.
if (a.progress !== undefined && typeof a.progress !== 'function') {
throw new Error(`registerEventActions: ${a.id} progress must be a function`)
}
const version = a.version === undefined ? 1 : a.version
if (!Number.isInteger(version) || version < 1) {
@@ -1150,6 +1243,7 @@ function checkEventActionShape(entry) {
perform: a.perform,
revert: a.revert || null,
reconcile: a.reconcile || null,
progress: a.progress || null,
}
}
@@ -1323,6 +1417,19 @@ function checkEventLeaseShape(entry) {
values = l.values.map((v) => String(v))
}
// **The lease's own example for its value** (MODULE_API 1.13.0; Rust
// PLAN_REDESIGNS §2.1, U-3). `core.lease`'s `value` param has one example for
// every lease there is, and a Rust admin borrowing a group permission was shown
// a skill-gain rate. Optional; a scalar, because it is a placeholder in one
// field. Not range-checked: it is shown, never sent.
let example = null
if (l.example !== undefined && l.example !== null && l.example !== '') {
if (!['string', 'number', 'boolean'].includes(typeof l.example)) {
throw new Error(`registerEventLeases: ${l.id} example must be a single value`)
}
example = l.example
}
return {
id: l.id,
label: l.label,
@@ -1331,6 +1438,7 @@ function checkEventLeaseShape(entry) {
min,
max,
values,
example,
target,
maxDurationMs,
read: l.read,
@@ -1377,6 +1485,56 @@ function checkEventOptionSourceShape(entry) {
}
}
// The most inputs a template may ask for. A template is a shortcut past the
// editor, and one that asks for a dozen things is the editor with fewer labels.
const MAX_TEMPLATE_INPUTS = 8
/**
* `registerEventTemplates([{ id, label, description, inputs, build }])`
* (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2.5, D192).
*
* A named starting point for a new event: the author fills in `inputs`, core
* calls `build({ inputs })`, and what comes back is a DRAFT the editor opens like
* any other — `{ title, summary?, spec: { phases } }`. Nothing about the template
* survives into the definition.
*
* **`inputs` are params, checked by the same function**, because they are drawn
* by the same widget: a name, a type, an example, maybe a source. That gives an
* input the dropdown, the search box and the duration unit for free, and gives
* the author one form language rather than two.
*
* `build` may be async and may read the module's own data (the kit weekend needs
* the kit's permission). It is never trusted: core checks the inputs before the
* call and validates the spec after it, and a throw is the author's error
* message rather than a 500 (`buildEventTemplate` in eventDefinitions.model).
*/
function checkEventTemplateShape(entry) {
const t = entry || {}
if (!EVENT_ID.test(t.id || '')) throw new Error(`registerEventTemplates: bad template id "${t.id}"`)
if (!t.label) throw new Error(`registerEventTemplates: template "${t.id}" has no label`)
if (typeof t.build !== 'function') throw new Error(`registerEventTemplates: ${t.id} has no build()`)
const rawInputs = t.inputs === undefined ? [] : t.inputs
if (!Array.isArray(rawInputs)) throw new Error(`registerEventTemplates: ${t.id} inputs must be an array`)
if (rawInputs.length > MAX_TEMPLATE_INPUTS) {
throw new Error(`registerEventTemplates: ${t.id} asks for ${rawInputs.length} inputs; the most is ${MAX_TEMPLATE_INPUTS}`)
}
const seen = new Set()
return {
id: t.id,
label: t.label,
description: t.description || '',
inputs: rawInputs.map((p) => checkActionParam(t.id, p, seen, 'registerEventTemplates')),
build: t.build,
}
}
/** Every template WITHOUT its `build` — what the catalog serves. */
const allEventTemplates = () =>
[...eventTemplates.values()].map(({ build, ...rest }) => rest)
/** One template, `build` included. */
const eventTemplate = (id) => eventTemplates.get(id) || null
// ── Engagement seeds (Phase 11b, decision 7) ───────────────────────────────
//
@@ -1621,6 +1779,7 @@ function stage(owner) {
eventBudgets: [],
eventLeases: [],
eventOptionSources: [],
eventTemplates: [],
}
return {
staged,
@@ -1679,6 +1838,12 @@ function stage(owner) {
if (!Array.isArray(entries)) throw new Error('registerEventOptionSources: expected an array')
for (const e of entries) staged.eventOptionSources.push(checkEventOptionSourceShape(e))
},
// MODULE_API 1.13.0. Core registers none; the first is Module-Rust's kit
// weekend (Rust PLAN_REDESIGNS §2.5).
registerEventTemplates(entries) {
if (!Array.isArray(entries)) throw new Error('registerEventTemplates: expected an array')
for (const e of entries) staged.eventTemplates.push(checkEventTemplateShape(e))
},
registerEngagementSeeds(entry) {
staged.engagementSeeds.push(checkEngagementSeeds(owner, entry))
},
@@ -1708,6 +1873,7 @@ function apply({
eventBudgets: newEventBudgets = [],
eventLeases: newEventLeases = [],
eventOptionSources: newEventOptionSources = [],
eventTemplates: newEventTemplates = [],
engagementSeeds: newSeeds = [],
}) {
// ── validate ──
@@ -1812,6 +1978,17 @@ function apply({
seenLeases.add(l.id)
}
const seenTemplates = new Set()
for (const t of newEventTemplates) {
const held = eventTemplates.get(t.id)
if (held) throw new Error(`event template "${t.id}" is already registered by "${held.owner}"`)
if (seenTemplates.has(t.id)) throw new Error(`event template "${t.id}" registered twice`)
if (!namespaced(owner, t.id, {})) {
throw new Error(`event template "${t.id}" is not namespaced "${owner}."`)
}
seenTemplates.add(t.id)
}
const seenSources = new Set()
for (const s of newEventOptionSources) {
const held = eventOptionSources.get(s.id)
@@ -1891,6 +2068,7 @@ function apply({
for (const b of newEventBudgets) eventBudgets.set(b.id, { owner, ...b })
for (const l of newEventLeases) eventLeases.set(l.id, { owner, ...l })
for (const s of newEventOptionSources) eventOptionSources.set(s.id, { owner, ...s })
for (const t of newEventTemplates) eventTemplates.set(t.id, { owner, ...t })
for (const seeds of newSeeds) engagementSeeds.set(owner, seeds)
}
@@ -1986,6 +2164,7 @@ function _reset() {
eventBudgets.clear()
eventLeases.clear()
eventOptionSources.clear()
eventTemplates.clear()
engagementSeeds.clear()
coreRegistered = false
}
@@ -2026,6 +2205,12 @@ module.exports = {
parseLeaseRef,
leaseRef,
allEventOptionSources,
allEventTemplates,
eventTemplate,
PARAM_DURATIONS,
MULTIPLE_PARAM_TYPES,
DEFAULT_MULTIPLE_MAX,
MAX_MULTIPLE_MAX,
resolveOptionSource,
allEngagementSeeds,
engagementSeedsFor,

View File

@@ -9,6 +9,58 @@
// Deliberately separate from PROTOCOL_VERSION (which versions the shard wire and
// has nothing to say about a website module) and from any module's own version.
// 1.15.0 — a failed step may say when to try again: `{ ok: false, retry: true,
// retryAfterMs }` (Rust PLAN_REDESIGNS §14.3.13, D371; docs/website/EVENTS.md §F).
// Clamped to one minute–thirty minutes, never refused; absent, the flat
// `EVENT_STEP_RETRY_MS` as before. It is one attempt of `EVENT_STEP_MAX_ATTEMPTS`
// like any retry, and ignored beside `retry: false`. One optional envelope
// member, so minor. Module-uo declares `^1.10.0` and answers none: an envelope
// without it is classified exactly as it was. This took 1.15.0 ahead of
// STEAM_SIGNIN.md, which had claimed it and moves to the next minor.
//
// 1.14.0 —an action param may hold several values: `multiple: true`, with an
// optional `max` (1–100, 20 if left out), on a `string` or `int` param (Rust
// PLAN_REDESIGNS §12.3, D344; docs/website/EVENTS.md §F). The step stores a JSON
// array; a bare value is read as a list of one; `required` means at least one;
// `perform()` and `cost()` are handed the array. Refused on a duration and on a
// template's inputs. The editor draws it as a multi-select.
// One optional flag, so minor. Module-uo declares `^1.10.0` and uses none of it:
// a param that does not say `multiple` is checked, stored and drawn exactly as it
// was, and the declaration the registry hands back does not grow the key.
//
// 1.13.0 — the event step editor (Rust PLAN_REDESIGNS §2; docs/website/EVENTS.md
// §F, §I). Four additions, each optional:
// • `api.registerEventTemplates([{ id, label, description, inputs, build }])` —
// a named starting point for a new event; inputs in, an ordinary draft out,
// and nothing about the template kept in the definition (D192);
// • a param's `duration: 'minutes'`, so the editor can see a timed step and
// keep its phase open long enough for it;
// • a lease's `example` for its value, so a lease step shows that lease's
// example rather than core's one for every lease;
// • an option row's `note`, shown under the field while it is the chosen one.
// Additions only, so minor. Module-uo declares `^1.10.0` and uses none of them:
// its actions, leases and sources come out of the registry exactly as they went
// in, and its steps render with the new controls and nothing else changed.
//
// 1.12.0 — an event action may declare `progress(envelope)`: how a live run's
// step stands, for its public page (docs/website/EVENTS.md §I; RunicNPC D304,
// D305). Core accepts two shapes, `{ label, left, of }` and `{ label, percent }`,
// puts them in the public run as `progress` and renders them as text it does not
// interpret. Optional and additive, so minor: Module-uo declares `^1.10.0` and
// registers no action with it, so its actions and pages are unchanged.
//
// 1.11.0 — `ctx.events.expired({ kind, ref })`, and `expired` as a resource
// ledger status (docs/website/EVENTS.md §L; Rust PLAN_FIXES D183). A game that
// ends something at its own deadline — a Rust zone erased when its time is up —
// could until now reach core only through `ctx.events.reconcile()`, which files
// it `orphaned`: amber, "it vanished", and still claimable for a revert. The new
// call files it as the plan working: terminal, green, never taken back.
//
// Additions only, so minor, and checked against the one module already built on
// 1.10.0: Module-uo never calls it, reads no ledger status, and every existing
// status keeps its meaning — `expired` joins neither `HELD` nor `UNRESOLVED`, so
// the sweep, the manual retry and `cleanup_status` see exactly what they saw.
// 1.10.0 — the event contract opens to modules: `api.registerEventActions`,
// `api.registerEventBudgets`, `api.registerEventLeases` and
// `api.registerEventOptionSources` (docs/website/EVENTS.md §F, EVENTS_PLAN.md
@@ -155,6 +207,6 @@
// an admin action a module performs belongs in core's one audit log, the
// extension slot needs the user its prefix names, and §2.7 forbids a module
// reading core's `APP_BASE_URL` for itself. Additions only, so minor.
const MODULE_API_VERSION = '1.10.0'
const MODULE_API_VERSION = '1.15.0'
module.exports = { MODULE_API_VERSION }

View File

@@ -34,6 +34,8 @@ const activity = require('../../../model/activity/activity.model')
const settingsDb = require('../../../model/events/eventActionSettings.db')
const authorize = require('../../../events/authorize')
const price = require('../../../events/price')
const starts = require('../../../events/starts')
const triggerStartsDb = require('../../../model/events/eventTriggerStarts.db')
const asId = (raw) => {
const n = Number(raw)
@@ -78,6 +80,19 @@ const shapeDefinition = (d) => ({
updatedAt: d.updated_at,
})
/**
* The definition as the EDITOR reads it: the shape above, and whether the working
* copy has moved on from the published version (Rust PLAN_REDESIGNS §2.3). One
* extra read, so only the three routes the editor loads from carry it.
*/
const shapeEditable = async (row) => ({
...shapeDefinition(row),
draftAhead: await definitions.draftAhead(row),
// What its trigger starts have done lately (D370): the last run one started
// and the firings ignored since, by why. Null until a trigger first tries.
triggerStarts: starts.describeState(await triggerStartsDb.forDefinition(row.id)),
})
const shapeRun = (r) => ({
id: r.id,
definitionId: r.definition_id,
@@ -95,6 +110,10 @@ const shapeRun = (r) => ({
concurrencyKey: r.concurrency_key,
params: r.params,
rehearsal: r.rehearsal,
// What started it, when a game firing did (D370): the trigger, when, its
// subject, the condition it matched and its declared variables. Null for a
// run started by hand or by the schedule.
origin: r.origin || null,
startedAt: r.started_at,
endedAt: r.ended_at,
// When the results table was ranked and published (Phase 10). On the LIST as
@@ -203,6 +222,9 @@ exports.catalog = (_req, res) => {
budgets: registries.allEventBudgets(),
leases: registries.allEventLeases(),
optionSources: registries.allEventOptionSources(),
// MODULE_API 1.13.0 (Rust PLAN_REDESIGNS §2.5). Without `build`, like every
// callable above; filling one in is its own request.
templates: registries.allEventTemplates(),
limits: {
maxPhases: spec.MAX_PHASES,
maxStepsPerPhase: spec.MAX_STEPS_PER_PHASE,
@@ -210,6 +232,9 @@ exports.catalog = (_req, res) => {
defaultBudgetMs: registries.DEFAULT_BUDGET_MS,
maxAdvanceCount: spec.MAX_ADVANCE_COUNT,
maxAfterSeconds: spec.MAX_AFTER_SECONDS,
// A definition's `starts` (D370): how many, and the cooldown's ceiling.
maxStarts: spec.MAX_STARTS,
maxCooldownSeconds: spec.MAX_COOLDOWN_SECONDS,
},
})
}
@@ -363,7 +388,7 @@ exports.get = async (req, res) => {
if (!id) return res.status(400).json({ error: 'bad event id' })
const row = await definitionsDb.getById(id)
if (!row) return res.status(404).json({ error: 'no such event definition' })
return res.json({ event: shapeDefinition(row) })
return res.json({ event: await shapeEditable(row) })
}
/** GET /api/v1/admin/events/:id/versions */
@@ -408,7 +433,7 @@ exports.update = async (req, res) => {
action: 'event.definition.updated',
detail: { id, title: result.definition.title },
})
return res.json({ event: shapeDefinition(result.definition) })
return res.json({ event: await shapeEditable(result.definition) })
}
/** POST /api/v1/admin/events/:id/publish */
@@ -423,7 +448,7 @@ exports.publish = async (req, res) => {
detail: { id, version: result.version, versionId: result.versionId, repinned: result.repinned },
})
return res.json({
event: shapeDefinition(result.definition),
event: await shapeEditable(result.definition),
version: result.version,
versionId: result.versionId,
// How many already-materialised occurrences moved to this version. The
@@ -585,6 +610,19 @@ exports.options = async (req, res) => {
return res.json(result)
}
/**
* POST /api/v1/admin/events/catalog/templates/:templateId — fill a template in.
*
* MODULE_API 1.13.0 (Rust PLAN_REDESIGNS §2.5). Answers a draft and writes
* nothing, so there is nothing to put in the activity log: the definition the
* draft becomes is logged when it is created, by the route that creates it.
*/
exports.buildTemplate = async (req, res) => {
const result = await definitions.buildFromTemplate(req.params.templateId, req.body?.inputs)
if (!result.ok) return res.status(result.status || 400).json({ errors: result.errors })
return res.json({ draft: result.draft })
}
/**
* PUT /api/v1/admin/events/actions — set one action's switch and caps.
*

View File

@@ -51,7 +51,7 @@ eventsRouter.get(
// #swagger.summary = 'List every registered event action, with its param schema, risk class and reversibility'
// #swagger.description = 'Served from the module registries, not from a table: an action is declared in code by core or by an installed module, so this is whatever registered on this boot, and an uninstalled module simply stops appearing. Core always declares core.announce, core.wait and core.cue. Also carries the closed vocabularies the authoring form renders — risk classes, reversibility classes, param types, failure dispositions and the spec size limits — so the editor offers exactly the set the save path checks against. Phase 5 added `triggers` and `operators`: the trigger catalog a module already ships IS the catalog of things a phase can advance on, and it is served here rather than borrowed from /admin/engagement/triggers because that route is admin-only while an event definition is authored by admin AND editor. Each trigger is reduced to its id, label and declared variables — a trigger's audience and ceiling are about who gets mailed, which is not this screen's question. Phase 7 added `budgets`, `leases` and `optionSources`: the other three registrations of the module contract, served beside the actions because the step editor needs all four to draw ONE step — the action says what params it takes, a param source names a dropdown, and a cap box is a budget label and unit. A source resolves its VALUES on a request of its own (/options/:sourceId), because a source can be slow or down and must not take the catalog with it.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The registered actions and triggers, and the vocabularies over them', content: { "application/json": { schema: { type: "object", properties: { actions: { type: "array", items: { type: "object", additionalProperties: true } }, triggers: { type: "array", items: { type: "object", additionalProperties: true } }, operators: { type: "array", items: { type: "object", additionalProperties: true } }, risks: { type: "array", items: { type: "string" } }, reversible: { type: "array", items: { type: "string" } }, paramTypes: { type: "array", items: { type: "string" } }, onFailure: { type: "array", items: { type: "string" } }, onFailureByRisk: { type: "object", additionalProperties: true }, scheduleKinds: { type: "array", items: { type: "string" } }, advanceKinds: { type: "array", items: { type: "string" } }, limits: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[200] = { description: 'The registered actions and triggers, and the vocabularies over them', content: { "application/json": { schema: { type: "object", properties: { actions: { type: "array", description: "Each action with its declared params. MODULE_API 1.14.0: a param may carry multiple: true and max (1 to 100, 20 when left out), and its value is then a JSON array of at most max values.", items: { type: "object", additionalProperties: true } }, triggers: { type: "array", items: { type: "object", additionalProperties: true } }, operators: { type: "array", items: { type: "object", additionalProperties: true } }, risks: { type: "array", items: { type: "string" } }, reversible: { type: "array", items: { type: "string" } }, paramTypes: { type: "array", items: { type: "string" } }, onFailure: { type: "array", items: { type: "string" } }, onFailureByRisk: { type: "object", additionalProperties: true }, scheduleKinds: { type: "array", items: { type: "string" } }, advanceKinds: { type: "array", items: { type: "string" } }, limits: { type: "object", additionalProperties: true }, templates: { type: "array", description: "Event templates (MODULE_API 1.13.0): id, label, description, owner and inputs (each shaped like an action param). build() is never served.", items: { type: "object", additionalProperties: true } } } } } } } */
/* #swagger.responses[403] = { description: 'Not staff', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
controller.catalog,
)
@@ -78,11 +78,35 @@ eventsRouter.get(
// object schema whose properties are `type` and `maxLength`, which documents a
// query parameter that takes a JSON object. The bound is stated in the description.
/* #swagger.parameters['q'] = { in: 'query', description: 'Narrow the list. Honoured only by a source that declares itself searchable; ignored, never refused, by the rest. Bounded to 120 characters.', required: false, schema: { type: 'string' } } */
/* #swagger.responses[200] = { description: 'The options, or the reason there are none', content: { "application/json": { schema: { type: "object", properties: { ok: { type: "boolean" }, id: { type: "string" }, label: { type: "string" }, owner: { type: "string" }, searchable: { type: "boolean" }, q: { type: "string" }, reason: { type: "string" }, options: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" }, group: { type: "string" } } } } } } } } } */
/* #swagger.responses[200] = { description: 'The options, or the reason there are none', content: { "application/json": { schema: { type: "object", properties: { ok: { type: "boolean" }, id: { type: "string" }, label: { type: "string" }, owner: { type: "string" }, searchable: { type: "boolean" }, q: { type: "string" }, reason: { type: "string" }, options: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" }, group: { type: "string" }, note: { type: "string", description: "Advice shown under the field while this option is chosen (MODULE_API 1.13.0). At most 300 characters." } } } } } } } } } */
/* #swagger.responses[403] = { description: 'Not staff', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
controller.options,
)
// ── Event templates (MODULE_API 1.13.0; Rust PLAN_REDESIGNS §2.5) ─────────
//
// Under `/catalog` for the reason the option sources are: a template is catalog
// data, and the nesting keeps it out of `/:id`'s way. A POST because the inputs
// are a body, not because anything is written — the answer is a draft the
// editor opens, and saving it is `POST /` with every rule that route has.
// `admin, editor`, because filling a template in is authoring.
eventsRouter.post(
'/catalog/templates/:templateId',
adminOrEditor,
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Fill an event template in, and get back a draft'
// #swagger.description = 'A module may register named event templates (MODULE_API 1.13.0). The catalog lists them with their inputs; this route checks the inputs against the template, calls the module to build the plan, validates the plan as a spec and answers it as a draft: a title, a summary and a spec. Nothing is saved, and nothing about the template is kept: the editor opens the draft like any new event and the author saves it through POST /admin/events. A refusal of the inputs is a 400 naming each problem; a module that fails or builds a plan core cannot accept is a 502.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", properties: { inputs: { type: "object", additionalProperties: true, description: "One value per declared input, keyed by its name" } } } } } } */
/* #swagger.responses[200] = { description: 'The draft', content: { "application/json": { schema: { type: "object", properties: { draft: { type: "object", properties: { title: { type: "string" }, summary: { type: "string", nullable: true }, spec: { type: "object", additionalProperties: true } } } } } } } } */
/* #swagger.responses[400] = { description: 'The inputs were refused', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or editor', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[404] = { description: 'No module registers that template', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[502] = { description: 'The module failed to build the plan, or built one core cannot accept', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
controller.buildTemplate,
)
// ── The live cap meter (Phase 13) ──────────────────────────────────
//
// A literal path for the same reason `/actions` is one, and `admin, editor` for
@@ -237,7 +261,7 @@ eventsRouter.get(
'/runs/:runId',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'One run: its status, health, cleanup state and every step with its params and idempotency key'
// #swagger.description = 'The run console. `counts` summarises the step list by status. Steps carry the idempotency key core minted at materialisation — stable across every attempt, which is what lets the game side recognise a repeat. `gates` is the diagnosis panel (Phase 5): one entry per phase that authored an advance condition, already rendered in the condition builder’s own words — `gte` as "is at least", `present` as "is present" — with the tally, how long it has waited, and the last related firing whether or not it matched. A phase is waiting on its gate only once every one of its steps is terminal; `stalled` means an `on` gate has waited past EVENT_PHASE_STALL_MS, which is visibility and never a timeout — nothing advances a phase but its condition or a human. `budget` is the cap meter (Phase 6), and `resources` is the cleanup ledger (Phase 8): every object this run created and every value it borrowed, with what became of each — `confirmed` is still out there, `reverted` came back, `drifted` means somebody moved it and core left it alone, and `orphaned` means the module reports it is gone. `unresolvedResources` counts the ones still wanting something, including a placeholder left standing by a lost acknowledgement, which is why it can exceed the length of the list. `participants` is who took part (Phase 10), best first, as a module reported them: `memberKey` is module-opaque, `userId` is filled in only where the module could link the player to an account, and `rank` is null until `core.results.publish` has ranked them — a run whose participants are collected but unranked is a real and visible state, not an error. The run itself carries `resultsPublishedAt`, which is when that table was last published.'
// #swagger.description = 'The run console. `counts` summarises the step list by status. Steps carry the idempotency key core minted at materialisation — stable across every attempt, which is what lets the game side recognise a repeat. `gates` is the diagnosis panel (Phase 5): one entry per phase that authored an advance condition, already rendered in the condition builder’s own words — `gte` as "is at least", `present` as "is present" — with the tally, how long it has waited, and the last related firing whether or not it matched. A phase is waiting on its gate only once every one of its steps is terminal; `stalled` means an `on` gate has waited past EVENT_PHASE_STALL_MS, which is visibility and never a timeout — nothing advances a phase but its condition or a human. `budget` is the cap meter (Phase 6), and `resources` is the cleanup ledger (Phase 8): every object this run created and every value it borrowed, with what became of each — `confirmed` is still out there, `reverted` came back, `drifted` means somebody moved it and core left it alone, `orphaned` means the module reports it is gone, and `expired` means the game ended it at its own deadline, as it was told to (terminal, like `reverted`). `unresolvedResources` counts the ones still wanting something, including a placeholder left standing by a lost acknowledgement, which is why it can exceed the length of the list. `participants` is who took part (Phase 10), best first, as a module reported them: `memberKey` is module-opaque, `userId` is filled in only where the module could link the player to an account, and `rank` is null until `core.results.publish` has ranked them — a run whose participants are collected but unranked is a real and visible state, not an error. The run itself carries `resultsPublishedAt`, which is when that table was last published, and `origin` when a game firing started it (Rust PLAN_REDESIGNS 14.3.12): the trigger, its label, when it fired, its subject, the start condition it matched in the builder words, and its declared variables. Null for a run started by hand or by the schedule.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The run, its steps, the status counts, the phase gates, the cap meter, the resource ledger and the participants', content: { "application/json": { schema: { type: "object", properties: { run: { type: "object", additionalProperties: true }, steps: { type: "array", items: { type: "object", additionalProperties: true } }, counts: { type: "object", additionalProperties: true }, gates: { type: "array", items: { type: "object", additionalProperties: true } }, budget: { type: "array", items: { type: "object", additionalProperties: true } }, resources: { type: "array", items: { type: "object", additionalProperties: true } }, unresolvedResources: { type: "integer" }, participants: { type: "array", items: { type: "object", additionalProperties: true } } } } } } } */
/* #swagger.responses[404] = { description: 'No such run', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
@@ -415,7 +439,7 @@ eventsRouter.get(
'/:id',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'One event definition, including its working spec'
// #swagger.description = 'The editor reads this. The list route serves a summary; this is the whole authored tree, phases and steps included.'
// #swagger.description = 'The editor reads this. The list route serves a summary; this is the whole authored tree, phases and steps included. The spec may carry `starts` (Rust PLAN_REDESIGNS 14.3.12): the triggers that begin a run of the published version, each a phase gate `on` and `where` plus a `cooldown` (0m to 7d, 30m when left out); core own event.* triggers are refused. `triggerStarts` is what they have done lately: the last run a trigger started and the firings ignored since, by why (a run was going, inside the cooldown, or the published version is not verified). Null until a trigger first tries.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The definition', content: { "application/json": { schema: { type: "object", properties: { event: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[404] = { description: 'No such definition', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */

View File

@@ -41,11 +41,12 @@ modulesRouter.post(
'/',
// #swagger.tags = ['Admin · Modules']
// #swagger.summary = 'Install or upgrade a module from a release install-manifest URL'
// #swagger.description = 'Downloads the artifact the manifest names, verifies its sha256, inspects the archive in full and unpacks it onto the modules volume. The module mounts on the next restart.'
// #swagger.description = 'Downloads the artifact the manifest names, verifies its sha256, inspects the archive in full and unpacks it onto the modules volume. The module mounts on the next restart. A site runs ONE module: installing a module other than the one already on the volume is refused with 409 before anything is downloaded, and only an upgrade of the installed module is accepted.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["url"], properties: { url: { type: "string", description: "https URL of the release install manifest, on an allowed host" } } } } } } */
/* #swagger.responses[201] = { description: 'Installed — restart to mount it', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[400] = { description: 'The URL, the manifest, the hash or the archive was refused', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'A different module is already installed; a site runs one module', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[502] = { description: 'The source host could not be reached or answered badly', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
body('url').isString().trim().isLength({ min: 1, max: 2048 }),

View File

@@ -50,7 +50,12 @@ async function getEvent(req, res) {
// string: the model matches it against this definition's own runs and
// ignores anything else, so a garbage value renders the page rather than an
// error. See the model's note on why it is not refused.
const result = await events.event(req.params.slug, { runId: req.query.run || null })
// `userId` is the reader's, when they sent a session (`optionalAuth`): a
// module's progress line may show a signed-in reader more than a stranger.
const result = await events.event(req.params.slug, {
runId: req.query.run || null,
userId: req.user && req.user.id != null ? req.user.id : null,
})
return answer(res, result)
} catch (err) {
return fail(res, err, 'public event')

View File

@@ -15,6 +15,7 @@ const express = require('express')
const ctrl = require('./events.controller')
const siteMode = require('../../../middleware/siteMode')
const { optionalAuth } = require('../../../auth/session.middleware')
const eventsRouter = express.Router()
@@ -48,12 +49,14 @@ eventsRouter.get(
'/:slug',
// #swagger.tags = ['Public · Events']
// #swagger.summary = 'One event'
// #swagger.description = 'The storyline, the arc it belongs to, what is live, what is next, what happened recently, and a results table once one has been published. A draft, an archived definition and an unlisted one all answer 404, indistinguishable from a slug that never existed. The plan behind the event — phases, steps, actions and their params — is never published; a live run carries the LABEL of the phase it is in and nothing more.'
// #swagger.description = 'The storyline, the arc it belongs to, what is live, what is next, what happened recently, and a results table once one has been published. A draft, an archived definition and an unlisted one all answer 404, indistinguishable from a slug that never existed. The plan behind the event — phases, steps, actions and their params — is never published; a live run carries the LABEL of the phase it is in and nothing more, and `progress`: how its steps stand, each line a label with either `left` of `of` or a `percent`, in the words the steps\' modules chose. What a module shows may depend on who is reading, so sending a session is optional and may widen it.'
// #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'The event slug.' }
// #swagger.parameters['run'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Which occurrence the results are about — what an announcement\'s link carries, so a mail about last Friday does not open next Friday\'s. A run that does not belong to this event is ignored rather than refused.' }
// #swagger.security = [{}, { "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The event', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicEvent" } } } } */
/* #swagger.responses[404] = { description: 'No such public event', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
siteMode,
optionalAuth,
ctrl.getEvent,
)

View File

@@ -24,6 +24,7 @@ const registries = require('../modules/registries')
const ceilings = require('../modules/ceilings')
const engine = require('../engagement/engine')
const eventGates = require('../events/gates')
const eventStarts = require('../events/starts')
const scopedPrefs = require('../engagement/scopedPrefs')
const createLogger = require('./logger')
@@ -320,6 +321,15 @@ function emit(owner, triggerId, envelope = {}) {
.observe(event)
.catch((err) => log.error('gate observation rejected', { trigger: triggerId, message: err.message }))
// **The third subscriber** (Rust PLAN_REDESIGNS §14.3.12, D370): a definition
// whose published version starts on this trigger gets a run, now. Separate
// from the gate observer for the same reason that one is separate from
// `dispatch` — starting a run and advancing one decide different things, and
// neither may fail the other.
eventStarts
.observe(event)
.catch((err) => log.error('trigger start rejected', { trigger: triggerId, message: err.message }))
return { ok: true, event }
}

View File

@@ -428,13 +428,28 @@ async function drainStep(run, step, now, carry = {}) {
}
if (result.outcome === 'retry' && step.attempts + 1 < MAX_ATTEMPTS) {
await stepsDb.reschedule(step.id, new Date(now.getTime() + RETRY_MS), result.error)
// The module's `retryAfterMs` when it gave one (already clamped by the
// dispatcher), else the flat delay. **It is still one attempt** of
// MAX_ATTEMPTS: a hint changes when, never how many, so a module that answers
// "not yet" for ever fails the step on schedule like any other. A run paused
// or cancelled in the wait is not picked up — `findDue` reads only running
// runs — and the staff Retry on a paused step is unaffected.
const delayMs = result.retryAfterMs || RETRY_MS
const retryAt = new Date(now.getTime() + delayMs)
await stepsDb.reschedule(step.id, retryAt, result.error)
await logDb.write({
runId: run.id,
stepId: step.id,
kind: 'step.retry',
phase: step.phase,
detail: { action: step.action_id, attempt: step.attempts + 1, of: MAX_ATTEMPTS, error: result.error },
detail: {
action: step.action_id,
attempt: step.attempts + 1,
of: MAX_ATTEMPTS,
error: result.error,
retryAt: retryAt.toISOString(),
...(result.retryAfterMs ? { retryAfterMs: result.retryAfterMs } : {}),
},
})
// Degraded from the FIRST retry, not from the eventual failure. An event
// whose announcements are landing on the second attempt is having trouble

View File

@@ -3869,6 +3869,7 @@
"properties": {
"actions": {
"type": "array",
"description": "Each action with its declared params. MODULE_API 1.14.0: a param may carry multiple: true and max (1 to 100, 20 when left out), and its value is then a JSON array of at most max values.",
"items": {
"type": "object",
"additionalProperties": true
@@ -3931,6 +3932,14 @@
"limits": {
"type": "object",
"additionalProperties": true
},
"templates": {
"type": "array",
"description": "Event templates (MODULE_API 1.13.0): id, label, description, owner and inputs (each shaped like an action param). build() is never served.",
"items": {
"type": "object",
"additionalProperties": true
}
}
}
}
@@ -4026,6 +4035,10 @@
},
"group": {
"type": "string"
},
"note": {
"type": "string",
"description": "Advice shown under the field while this option is chosen (MODULE_API 1.13.0). At most 300 characters."
}
}
}
@@ -4056,6 +4069,144 @@
]
}
},
"/api/v1/admin/events/catalog/templates/{templateId}": {
"post": {
"tags": [
"Admin · Events"
],
"summary": "Fill an event template in, and get back a draft",
"description": "A module may register named event templates (MODULE_API 1.13.0). The catalog lists them with their inputs; this route checks the inputs against the template, calls the module to build the plan, validates the plan as a spec and answers it as a draft: a title, a summary and a spec. Nothing is saved, and nothing about the template is kept: the editor opens the draft like any new event and the author saves it through POST /admin/events. A refusal of the inputs is a 400 naming each problem; a module that fails or builds a plan core cannot accept is a 502.",
"parameters": [
{
"name": "templateId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "The draft",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"draft": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"summary": {
"type": "string",
"nullable": true
},
"spec": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
},
"400": {
"description": "The inputs were refused",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"errors": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
},
"403": {
"description": "Not an admin or editor",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "No module registers that template",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"errors": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
},
"502": {
"description": "The module failed to build the plan, or built one core cannot accept",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"errors": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
},
"security": [
{
"cookieAuth": []
},
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"inputs": {
"type": "object",
"additionalProperties": true,
"description": "One value per declared input, keyed by its name"
}
}
}
}
}
}
}
},
"/api/v1/admin/events/price": {
"post": {
"tags": [
@@ -4271,7 +4422,7 @@
"Admin · Events"
],
"summary": "One run: its status, health, cleanup state and every step with its params and idempotency key",
"description": "The run console. `counts` summarises the step list by status. Steps carry the idempotency key core minted at materialisation — stable across every attempt, which is what lets the game side recognise a repeat. `gates` is the diagnosis panel (Phase 5): one entry per phase that authored an advance condition, already rendered in the condition builder’s own words — `gte` as \"is at least\", `present` as \"is present\" — with the tally, how long it has waited, and the last related firing whether or not it matched. A phase is waiting on its gate only once every one of its steps is terminal; `stalled` means an `on` gate has waited past EVENT_PHASE_STALL_MS, which is visibility and never a timeout — nothing advances a phase but its condition or a human. `budget` is the cap meter (Phase 6), and `resources` is the cleanup ledger (Phase 8): every object this run created and every value it borrowed, with what became of each — `confirmed` is still out there, `reverted` came back, `drifted` means somebody moved it and core left it alone, and `orphaned` means the module reports it is gone. `unresolvedResources` counts the ones still wanting something, including a placeholder left standing by a lost acknowledgement, which is why it can exceed the length of the list. `participants` is who took part (Phase 10), best first, as a module reported them: `memberKey` is module-opaque, `userId` is filled in only where the module could link the player to an account, and `rank` is null until `core.results.publish` has ranked them — a run whose participants are collected but unranked is a real and visible state, not an error. The run itself carries `resultsPublishedAt`, which is when that table was last published.",
"description": "The run console. `counts` summarises the step list by status. Steps carry the idempotency key core minted at materialisation — stable across every attempt, which is what lets the game side recognise a repeat. `gates` is the diagnosis panel (Phase 5): one entry per phase that authored an advance condition, already rendered in the condition builder’s own words — `gte` as \"is at least\", `present` as \"is present\" — with the tally, how long it has waited, and the last related firing whether or not it matched. A phase is waiting on its gate only once every one of its steps is terminal; `stalled` means an `on` gate has waited past EVENT_PHASE_STALL_MS, which is visibility and never a timeout — nothing advances a phase but its condition or a human. `budget` is the cap meter (Phase 6), and `resources` is the cleanup ledger (Phase 8): every object this run created and every value it borrowed, with what became of each — `confirmed` is still out there, `reverted` came back, `drifted` means somebody moved it and core left it alone, `orphaned` means the module reports it is gone, and `expired` means the game ended it at its own deadline, as it was told to (terminal, like `reverted`). `unresolvedResources` counts the ones still wanting something, including a placeholder left standing by a lost acknowledgement, which is why it can exceed the length of the list. `participants` is who took part (Phase 10), best first, as a module reported them: `memberKey` is module-opaque, `userId` is filled in only where the module could link the player to an account, and `rank` is null until `core.results.publish` has ranked them — a run whose participants are collected but unranked is a real and visible state, not an error. The run itself carries `resultsPublishedAt`, which is when that table was last published, and `origin` when a game firing started it (Rust PLAN_REDESIGNS 14.3.12): the trigger, its label, when it fired, its subject, the start condition it matched in the builder words, and its declared variables. Null for a run started by hand or by the schedule.",
"parameters": [
{
"name": "runId",
@@ -5552,7 +5703,7 @@
"Admin · Events"
],
"summary": "One event definition, including its working spec",
"description": "The editor reads this. The list route serves a summary; this is the whole authored tree, phases and steps included.",
"description": "The editor reads this. The list route serves a summary; this is the whole authored tree, phases and steps included. The spec may carry `starts` (Rust PLAN_REDESIGNS 14.3.12): the triggers that begin a run of the published version, each a phase gate `on` and `where` plus a `cooldown` (0m to 7d, 30m when left out); core own event.* triggers are refused. `triggerStarts` is what they have done lately: the last run a trigger started and the firings ignored since, by why (a run was going, inside the cooldown, or the published version is not verified). Null until a trigger first tries.",
"parameters": [
{
"name": "id",
@@ -7211,7 +7362,7 @@
"Admin · Modules"
],
"summary": "Install or upgrade a module from a release install-manifest URL",
"description": "Downloads the artifact the manifest names, verifies its sha256, inspects the archive in full and unpacks it onto the modules volume. The module mounts on the next restart.",
"description": "Downloads the artifact the manifest names, verifies its sha256, inspects the archive in full and unpacks it onto the modules volume. The module mounts on the next restart. A site runs ONE module: installing a module other than the one already on the volume is refused with 409 before anything is downloaded, and only an upgrade of the installed module is accepted.",
"responses": {
"201": {
"description": "Installed — restart to mount it",
@@ -7234,6 +7385,16 @@
}
}
},
"409": {
"description": "A different module is already installed; a site runs one module",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"500": {
"description": "Internal Server Error"
},
@@ -17338,7 +17499,7 @@
"Public · Events"
],
"summary": "One event",
"description": "The storyline, the arc it belongs to, what is live, what is next, what happened recently, and a results table once one has been published. A draft, an archived definition and an unlisted one all answer 404, indistinguishable from a slug that never existed. The plan behind the event — phases, steps, actions and their params — is never published; a live run carries the LABEL of the phase it is in and nothing more.",
"description": "The storyline, the arc it belongs to, what is live, what is next, what happened recently, and a results table once one has been published. A draft, an archived definition and an unlisted one all answer 404, indistinguishable from a slug that never existed. The plan behind the event — phases, steps, actions and their params — is never published; a live run carries the LABEL of the phase it is in and nothing more, and `progress`: how its steps stand, each line a label with either `left` of `of` or a `percent`, in the words the steps\\' modules chose. What a module shows may depend on who is reading, so sending a session is optional and may widen it.",
"parameters": [
{
"name": "slug",
@@ -17383,7 +17544,16 @@
"503": {
"description": "Service Unavailable"
}
}
},
"security": [
{},
{
"cookieAuth": []
},
{
"bearerAuth": []
}
]
}
},
"/api/v1/public/modules": {
@@ -26295,6 +26465,23 @@
}
}
},
"runId": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "integer"
},
"example": {
"type": "number",
"example": 3692
},
"description": {
"type": "string",
"example": "Runs only: the run this entry is, the same id `PublicEventOccurrence.runId` carries and `/events/{slug}?run=` takes. A projected entry has none, because nothing is committed to it."
}
}
},
"title": {
"type": "object",
"properties": {
@@ -26724,6 +26911,100 @@
"example": true
}
}
},
"progress": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "array"
},
"description": {
"type": "string",
"example": "On the live occurrence only: how its steps stand, in step order, in the words their modules chose (MODULE_API 1.12.0). Each line is a `label` with either `left` of `of` (\"Bandits: 3 of 8 left\") or a `percent` (\"The Juggernaut: 62%\"). Core renders them as text and interprets nothing. Empty when no step has anything to say, or its module did not answer in time."
},
"items": {
"$ref": "#/components/schemas/PublicEventProgressLine"
}
}
}
}
}
}
},
"PublicEventProgressLine": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "object"
},
"description": {
"type": "string",
"example": "One line of a live run’s progress: a `label` with either `left` of `of`, or a `percent`. Never both."
},
"properties": {
"type": "object",
"properties": {
"label": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "string"
},
"example": {
"type": "string",
"example": "Bandits"
}
}
},
"left": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "integer"
},
"example": {
"type": "number",
"example": 3
}
}
},
"of": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "integer"
},
"example": {
"type": "number",
"example": 8
}
}
},
"percent": {
"type": "object",
"properties": {
"type": {
"type": "string",
"example": "integer"
},
"minimum": {
"type": "number",
"example": 0
},
"maximum": {
"type": "number",
"example": 100
},
"example": {
"type": "number",
"example": 62
}
}
}
}
}

View File

@@ -1247,6 +1247,12 @@ const doc = {
'One calendar entry. `kind` says which of two things it is: a `run` is a materialised occurrence, a `projected` entry is arithmetic past the materialisation horizon — a forecast with nothing committed to it, which a client should draw as such.',
properties: {
kind: { type: 'string', enum: ['run', 'projected'], example: 'run' },
runId: {
type: 'integer',
example: 3692,
description:
'Runs only: the run this entry is, the same id `PublicEventOccurrence.runId` carries and `/events/{slug}?run=` takes. A projected entry has none, because nothing is committed to it.',
},
title: { type: 'string', example: 'The Yew Invasion' },
slug: { type: 'string', example: 'the-yew-invasion' },
seriesName: { type: 'string', nullable: true, example: 'The Yew Campaign' },
@@ -1312,6 +1318,23 @@ const doc = {
'The LABEL of the phase a live run is in, resolved from the version the run pinned. Null unless it is live. The plan behind the event — phases, steps, actions and their params — is never published.',
},
resultsPublishedAt: { type: 'string', format: 'date-time', nullable: true },
progress: {
type: 'array',
description:
'On the live occurrence only: how its steps stand, in step order, in the words their modules chose (MODULE_API 1.12.0). Each line is a `label` with either `left` of `of` ("Bandits: 3 of 8 left") or a `percent` ("The Juggernaut: 62%"). Core renders them as text and interprets nothing. Empty when no step has anything to say, or its module did not answer in time.',
items: { $ref: '#/components/schemas/PublicEventProgressLine' },
},
},
},
PublicEventProgressLine: {
type: 'object',
description:
'One line of a live run’s progress: a `label` with either `left` of `of`, or a `percent`. Never both.',
properties: {
label: { type: 'string', example: 'Bandits' },
left: { type: 'integer', example: 3 },
of: { type: 'integer', example: 8 },
percent: { type: 'integer', minimum: 0, maximum: 100, example: 62 },
},
},
PublicEventParticipant: {

View File

@@ -187,6 +187,16 @@ test("reversible: 'ledger' without revert() is refused at registration", () => {
assert.equal(typeof registries.eventAction('demo.thing.do').revert, 'function')
})
test('progress() is optional, must be a function, and never reaches the catalog (1.12.0)', () => {
assert.throws(() => register('demo', [ok({ progress: { label: 'x' } })]), /progress must be a function/)
register('demo', [ok({ progress: async () => ({ label: 'Things', left: 1, of: 2 }) })])
assert.equal(typeof registries.eventAction('demo.thing.do').progress, 'function')
assert.equal(registries.allEventActions().find((a) => a.id === 'demo.thing.do').progress, undefined)
registries._reset()
register('demo', [ok()])
assert.equal(registries.eventAction('demo.thing.do').progress, null)
})
test('perform() is required and cost must be a function', () => {
assert.throws(() => register('demo', [ok({ perform: undefined })]), /has no perform\(\)/)
assert.throws(() => register('demo', [ok({ cost: { 'demo.things': 1 } })]), /cost must be a function/)

View File

@@ -101,6 +101,7 @@ beforeEach(() => {
...new Set([...store.rows.values()].filter((r) => ['pending', 'confirmed'].includes(r.status)).map((r) => r.owner_module)),
]
resourcesDb.runsNeedingCleanup = async () => store.candidates || []
resourcesDb.finishedRunsWithNothingLeft = async () => store.nothingLeft || []
runsDb.setCleanupStatus = async (id, to, from = null) => {
if (from && !from.includes(store.cleanupStatus)) return false
@@ -618,3 +619,130 @@ test('reconcileAll asks every module that owns a live row', async () => {
// orphaned by a module that is not there to be asked.
assert.equal(out.other.unanswered, 1)
})
// ── Expiry (MODULE_API 1.11.0, Rust PLAN_FIXES D183) ─────────────────────────
//
// A game that ends something at its own deadline — a Rust zone erased when its
// time is up — says so through `ctx.events.expired`. The properties:
//
// • **expired is terminal**: the sweep never tries to give it back, and it is
// not one of the statuses that makes a run's cleanup unfinished
// • **it is not orphaned**, and it wins over orphaned: a reconcile that ran
// before the module heard the expiry filed the row as vanished
// • **a module closes only its own rows**, and only the target it named
// • **a revert already in flight is left to finish** — it finds nothing, which
// §L calls a success, and settles as `reverted` by itself
// • **a finished run whose last row this was is complete**, even one the sweep
// had given up on as `incomplete`
function stubExpiry() {
resourcesDb.expirableByTarget = async (owner, kind, ref) =>
[...store.rows.values()]
.filter((r) => r.owner_module === owner && r.kind === kind && r.ref === ref)
.filter((r) => ['pending', 'confirmed', 'orphaned'].includes(r.status))
.map((r) => ({ ...r }))
resourcesDb.markExpired = async (id, detail = null) => {
const r = store.rows.get(id)
if (!r || !['pending', 'confirmed', 'orphaned'].includes(r.status)) return false
Object.assign(r, { status: 'expired', last_error: detail })
return true
}
store.run = { ...RUN }
runsDb.getById = async (id) => (id === RUN.id ? store.run : null)
}
test('an expired resource is terminal: the sweep never tries to give it back', async () => {
stubExpiry()
let reverts = 0
registerAction({ revert: async () => { reverts += 1; return { ok: true } } })
addStep(1, 'demo.spawn')
addResource({ kind: 'zone', ref: '3:rg-7-1' })
assert.deepEqual(await cleanup.expireResource('demo', { kind: 'zone', ref: '3:rg-7-1' }), { expired: 1 })
const row = [...store.rows.values()][0]
assert.equal(row.status, 'expired')
assert.ok(store.log.some((e) => e.kind === 'resource.expired' && e.detail.resource === 'zone:3:rg-7-1'))
const summary = await cleanup.cleanupRun(RUN)
assert.equal(summary.attempted, 0)
assert.equal(reverts, 0)
assert.equal(row.status, 'expired')
assert.equal(store.cleanupStatus, 'complete')
})
test('an expiry wins over orphaned, and leaves a revert in flight alone', async () => {
stubExpiry()
addResource({ kind: 'zone', ref: 'a', status: 'orphaned' })
addResource({ kind: 'zone', ref: 'b', status: 'reverting' })
addResource({ kind: 'zone', ref: 'c', status: 'reverted' })
for (const ref of ['a', 'b', 'c']) await cleanup.expireResource('demo', { kind: 'zone', ref })
const status = (ref) => [...store.rows.values()].find((r) => r.ref === ref).status
assert.equal(status('a'), 'expired')
assert.equal(status('b'), 'reverting')
assert.equal(status('c'), 'reverted')
})
test('a module closes only its own rows, and only the target it named', async () => {
stubExpiry()
addResource({ owner_module: 'demo', kind: 'zone', ref: 'x' })
addResource({ owner_module: 'other', kind: 'zone', ref: 'x' })
addResource({ owner_module: 'demo', kind: 'npc', ref: 'x' })
assert.deepEqual(await cleanup.expireResource('demo', { kind: 'zone', ref: 'x' }), { expired: 1 })
const rows = [...store.rows.values()]
assert.deepEqual(rows.map((r) => r.status), ['expired', 'confirmed', 'confirmed'])
})
test('an expiry nobody ledgered, or a malformed one, is not an error', async () => {
stubExpiry()
addResource({ kind: 'zone', ref: 'x' })
for (const bad of [undefined, {}, { kind: 'zone' }, { ref: 'x' }, { kind: 1, ref: 'x' }, { kind: 'zone', ref: 'y' },
{ kind: 'zone', ref: 'r'.repeat(191) }]) {
assert.deepEqual(await cleanup.expireResource('demo', bad), { expired: 0 }, JSON.stringify(bad))
}
assert.equal([...store.rows.values()][0].status, 'confirmed')
assert.equal(store.log.length, 0)
})
test('the last row of a finished run expiring completes an incomplete cleanup', async () => {
stubExpiry()
addResource({ kind: 'zone', ref: 'x' })
store.cleanupStatus = 'incomplete'
await cleanup.expireResource('demo', { kind: 'zone', ref: 'x' })
assert.equal(store.cleanupStatus, 'complete')
})
test('a run still in flight keeps its cleanup status, and so does one with rows left', async () => {
stubExpiry()
addResource({ kind: 'zone', ref: 'x' })
store.run = { ...RUN, status: 'running' }
store.cleanupStatus = 'pending'
await cleanup.expireResource('demo', { kind: 'zone', ref: 'x' })
assert.equal(store.cleanupStatus, 'pending')
store.rows.clear()
addResource({ kind: 'zone', ref: 'y' })
addResource({ kind: 'zone', ref: 'z' })
store.run = { ...RUN }
store.cleanupStatus = 'incomplete'
await cleanup.expireResource('demo', { kind: 'zone', ref: 'y' })
assert.equal(store.cleanupStatus, 'incomplete')
})
test('a run whose last resource expired while it ran is settled complete when it ends', async () => {
// The step-2 walk's run 46: the zone expired while the run was still going, so
// expireResource left its status to the terminal path — and the sweep's scan,
// which joins on an unresolved row, would never have selected it. `pending`
// for ever, on a ledger with nothing left in it.
store.cleanupStatus = 'pending'
store.candidates = []
store.nothingLeft = [RUN.id]
assert.equal(await cleanup.sweep(), 1)
assert.equal(store.cleanupStatus, 'complete')
// And never over an incomplete one — that is a human's to clear.
store.cleanupStatus = 'incomplete'
await cleanup.sweep()
assert.equal(store.cleanupStatus, 'incomplete')
})

View File

@@ -38,6 +38,7 @@ const { test, beforeEach, after } = require('node:test')
const assert = require('node:assert/strict')
const express = require('express')
const semver = require('../src/modules/semver')
const db = require('../src/utils/db')
const registries = require('../src/modules/registries')
@@ -99,13 +100,19 @@ beforeEach(() => {
// ── The seam is open ───────────────────────────────────────────────────────
test('the version a module declares against is 1.10.0', () => {
test('the version a module declares against satisfies ^1.10.0', () => {
// Not decoration. `coreApi: "^1.10.0"` on every module below is what makes
// these tests fail loudly rather than quietly if the bump is ever reverted —
// the loader would refuse the manifest and every assertion would become "the
// module did not register", which is the same failure the seam closing would
// produce. Asserting the number here says which of the two it was.
assert.equal(MODULE_API_VERSION, '1.10.0')
// produce. Asserting the range here says which of the two it was.
//
// A range, not the number, since 1.11.0 (`ctx.events.expired`, Rust
// PLAN_FIXES D183): an additive bump must keep every module written against
// 1.10.0 loading — Module-uo declares exactly `^1.10.0` — and this is the
// assertion that says it does. The number itself is pinned in version.js.
assert.ok(semver.satisfies(MODULE_API_VERSION, '^1.10.0'), MODULE_API_VERSION)
assert.equal(MODULE_API_VERSION, '1.15.0')
})
test('a module registers actions, budgets, leases and option sources', () => {

View File

@@ -0,0 +1,157 @@
// ── A param that holds several values (MODULE_API 1.14.0) ──────────────────
//
// Rust PLAN_REDESIGNS §12.3 (D344): `multiple: true` (+ `max`) on a string or int
// action param. The declaration is checked at registration, the value at save —
// a JSON array, a bare value read as a list of one, duplicates dropped in order,
// `required` meaning at least one — and `cost()` is priced with a list. A param
// that does not say `multiple` must come out of the registry exactly as it went
// in: that is what keeps Module-uo's `^1.10.0` honest.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test, beforeEach, afterEach, after } = require('node:test')
const assert = require('node:assert/strict')
const registries = require('../src/modules/registries')
const spec = require('../src/events/spec')
const authorize = require('../src/events/authorize')
const db = require('../src/utils/db')
after(() => db.close())
const register = (actions, budgets = []) => {
const api = registries.stage('demo')
if (budgets.length) api.registerEventBudgets(budgets)
api.registerEventActions(actions)
registries.apply(api.staged)
}
const action = (params, extra = {}) => ({
id: 'demo.perk.lend',
label: 'Lend perks',
risk: 'notify',
reversible: 'none',
params,
perform: async () => ({ ok: true }),
...extra,
})
const perms = (extra = {}) => ({ name: 'perms', type: 'string', required: true, example: 'nightvision.allowed', multiple: true, ...extra })
beforeEach(() => {
registries._reset()
registries.registerCore()
})
afterEach(() => registries._reset())
const oneStep = (params) => ({
schedule: { kind: 'manual' },
phases: [{ key: 'main', label: 'Main', steps: [{ actionId: 'demo.perk.lend', params }] }],
})
// ── The declaration ───────────────────────────────────────────────────────
test('multiple is served with its max, 20 when left out', () => {
register([action([perms(), { name: 'ids', type: 'int', example: 7, multiple: true, max: 5 }])])
const [p, ids] = registries.eventAction('demo.perk.lend').params
assert.equal(p.multiple, true)
assert.equal(p.max, registries.DEFAULT_MULTIPLE_MAX)
assert.equal(ids.max, 5)
const served = registries.allEventActions().find((a) => a.id === 'demo.perk.lend')
assert.equal(served.params[0].multiple, true)
assert.equal(served.params[1].max, 5)
})
test('a param that does not say multiple does not grow the key', () => {
register([action([{ name: 'region', type: 'string', example: 'Yew' }, perms({ multiple: false })])])
for (const p of registries.eventAction('demo.perk.lend').params) {
assert.equal('multiple' in p, false)
assert.equal('max' in p, false)
}
// Core's own actions say none of it either.
for (const a of registries.allEventActions().filter((x) => x.owner === 'core')) {
for (const p of a.params) assert.equal('multiple' in p, false, `${a.id}.${p.name}`)
}
})
test('multiple is refused on a type, a duration, a bad max and a list example', () => {
const refused = (param, pattern) => assert.throws(() => register([action([param])]), pattern)
refused(perms({ type: 'boolean', example: true }), /is multiple and must be string or int, not boolean/)
refused(perms({ type: 'float', example: 1.5 }), /is multiple and must be string or int, not float/)
refused(perms({ type: 'int', example: 5, duration: 'minutes' }), /cannot be both multiple and a duration/)
refused(perms({ max: 0 }), /max must be 1\.\.100/)
refused(perms({ max: 101 }), /max must be 1\.\.100/)
refused(perms({ max: 2.5 }), /max must be 1\.\.100/)
refused(perms({ multiple: 'yes' }), /multiple must be true or left out/)
refused(perms({ example: ['a', 'b'] }), /needs ONE example, not a list/)
refused({ name: 'region', type: 'string', example: 'Yew', max: 3 }, /has a max but is not multiple/)
})
test('a template input cannot be multiple', () => {
const api = registries.stage('demo')
assert.throws(
() => api.registerEventTemplates([{
id: 'demo.template.perks',
label: 'Perks',
inputs: [perms()],
build: async () => null,
}]),
/input "perms" cannot be multiple/,
)
})
// ── The value ─────────────────────────────────────────────────────────────
test('a list is kept in order, deduplicated, and a bare value is a list of one', () => {
register([action([perms(), { name: 'ids', type: 'int', example: 7, multiple: true }])])
const listed = spec.validate(oneStep({ perms: ['b.two', 'a.one', 'b.two'], ids: [3, 1, 3] }))
assert.equal(listed.ok, true, listed.errors?.join('; '))
assert.deepEqual(listed.spec.phases[0].steps[0].params, { perms: ['b.two', 'a.one'], ids: [3, 1] })
const bare = spec.validate(oneStep({ perms: 'nightvision.allowed', ids: 9 }))
assert.equal(bare.ok, true, bare.errors?.join('; '))
assert.deepEqual(bare.spec.phases[0].steps[0].params, { perms: ['nightvision.allowed'], ids: [9] })
})
test('required means at least one; an optional empty list is left out', () => {
register([action([perms(), { name: 'ids', type: 'int', example: 7, multiple: true }])])
for (const empty of [undefined, null, '', []]) {
const r = spec.validate(oneStep(empty === undefined ? {} : { perms: empty }))
assert.equal(r.ok, false, JSON.stringify(empty))
assert.match(r.errors.join('\n'), /"perms" is required/)
}
const r = spec.validate(oneStep({ perms: ['a.one'], ids: [] }))
assert.equal(r.ok, true, r.errors?.join('; '))
assert.equal('ids' in r.spec.phases[0].steps[0].params, false)
})
test('each item is the type, none is empty, and max is a ceiling', () => {
register([action([perms({ max: 2 }), { name: 'ids', type: 'int', example: 7, multiple: true }])])
const errs = (params) => spec.validate(oneStep(params)).errors?.join('\n') || ''
assert.match(errs({ perms: ['a', 4] }), /"perms" item 2 expected a string/)
assert.match(errs({ perms: ['a', ''] }), /"perms" item 2 is empty/)
assert.match(errs({ perms: ['a'], ids: [1, 'two'] }), /"ids" item 2 expected an integer/)
assert.match(errs({ perms: ['a', 'b', 'c'] }), /"perms" holds 3 values; the most is 2/)
// A duplicate does not count against max.
assert.equal(spec.validate(oneStep({ perms: ['a', 'b', 'a'] })).ok, true)
assert.match(errs({ perms: [['nested']] }), /"perms" item 1 expected a string/)
})
// ── The price ─────────────────────────────────────────────────────────────
test('cost() is handed the list, and its dimensions are found from a list of one', () => {
const seen = []
register(
[action([perms()], {
cost: (params) => {
seen.push(params.perms)
return { 'demo.perks': (params.perms || []).length }
},
})],
[{ id: 'demo.perks', label: 'Perks', unit: 'perks' }],
)
const declared = registries.eventAction('demo.perk.lend')
assert.deepEqual(authorize.dimensionsOf(declared), ['demo.perks'])
assert.deepEqual(seen.at(-1), ['nightvision.allowed'])
assert.deepEqual(authorize.priceOf(declared, { perms: ['a', 'b', 'c'] }), { 'demo.perks': 3 })
})

View File

@@ -0,0 +1,174 @@
// ── A live run's progress lines (MODULE_API 1.12.0) ────────────────────────
//
// `events/progress.js`: core asks each step whose action declares `progress()`
// how it stands, and publishes two shapes it never interprets. What is worth
// testing is the contract's edges:
//
// • only the two shapes pass, a count and a percentage, each with a label;
// anything else is dropped, never repaired
// • a module that throws, answers late or is uninstalled costs a line, not the
// page: `forRun` never rejects
// • a step is asked with ITS ledger rows only, still held, and the reader's id
// • one answer per run and reader for the cache window
//
// Stubbed at the `.db` layer and the registry, like `eventPublic.test.js`.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test, beforeEach, afterEach, after } = require('node:test')
const assert = require('node:assert/strict')
const progress = require('../src/events/progress')
const registries = require('../src/modules/registries')
const stepsDb = require('../src/model/events/eventRunSteps.db')
const resourcesDb = require('../src/model/events/eventRunResources.db')
const db = require('../src/utils/db')
after(() => db.close())
const originals = { steps: { ...stepsDb }, resources: { ...resourcesDb } }
let steps
let ledger
beforeEach(() => {
registries._reset()
progress._reset()
steps = []
ledger = []
stepsDb.listForRun = async () => steps
resourcesDb.forRun = async () => ledger
})
afterEach(() => {
Object.assign(stepsDb, originals.steps)
Object.assign(resourcesDb, originals.resources)
registries._reset()
progress._reset()
})
const register = (entries) => {
const api = registries.stage('demo')
api.registerEventActions(entries)
registries.apply(api.staged)
}
const action = (over = {}) => ({
id: 'demo.npc.place',
label: 'Place',
risk: 'change',
reversible: 'ledger',
perform: async () => ({ ok: true }),
revert: async () => ({ ok: true }),
...over,
})
const step = (id, actionId = 'demo.npc.place', params = {}) => ({
id,
action_id: actionId,
params,
idempotency_key: `key-${id}`,
})
const RUN = { id: 7, scope: '' }
test('only a count or a percent, each with a label, is a line', () => {
assert.deepEqual(progress.toLine({ label: 'Bandits', left: 3, of: 8 }, 'a'), { label: 'Bandits', left: 3, of: 8 })
assert.deepEqual(progress.toLine({ label: 'The Juggernaut', percent: 61.6 }, 'a'), { label: 'The Juggernaut', percent: 62 })
assert.equal(progress.toLine(null, 'a'), null)
assert.equal(progress.toLine('3 of 8', 'a'), null)
assert.equal(progress.toLine({ left: 3, of: 8 }, 'a'), null, 'no label')
assert.equal(progress.toLine({ label: 'x'.repeat(progress.MAX_LABEL + 1), left: 1, of: 1 }, 'a'), null)
assert.equal(progress.toLine({ label: 'Both', left: 1, of: 2, percent: 50 }, 'a'), null)
assert.equal(progress.toLine({ label: 'More left than placed', left: 9, of: 8 }, 'a'), null)
assert.equal(progress.toLine({ label: 'Nothing placed', left: 0, of: 0 }, 'a'), null)
assert.equal(progress.toLine({ label: 'Half', left: 1.5, of: 3 }, 'a'), null)
assert.equal(progress.toLine({ label: 'Over', percent: 101 }, 'a'), null)
assert.equal(progress.toLine({ label: 'Text', percent: '50' }, 'a'), null)
// Extra keys do not ride along: core publishes what it validated.
assert.deepEqual(progress.toLine({ label: 'B', left: 0, of: 1, secret: 'x' }, 'a'), { label: 'B', left: 0, of: 1 })
})
test('each step is asked with its own held rows and the reader, in step order', async () => {
const seen = []
register([
action({
progress: async (env) => {
seen.push(env)
return { label: `Step ${env.stepId}`, left: env.resources.length, of: 2 }
},
}),
])
steps = [step(1), step(2)]
ledger = [
{ step_id: 1, kind: 'npc', ref: 'a', payload: null, status: 'confirmed' },
{ step_id: 1, kind: 'npc', ref: 'b', payload: null, status: 'reverted' },
{ step_id: 2, kind: 'npc', ref: 'c', payload: null, status: 'confirmed' },
{ step_id: 2, kind: 'npc', ref: 'd', payload: null, status: 'pending' },
{ step_id: 2, kind: resourcesDb.STEP_KIND, ref: '2', payload: null, status: 'confirmed' },
]
const lines = await progress.forRun(RUN, { viewer: { userId: 42 } })
assert.deepEqual(lines, [
{ label: 'Step 1', left: 1, of: 2 },
{ label: 'Step 2', left: 2, of: 2 },
])
assert.deepEqual(seen[0].resources, [{ kind: 'npc', ref: 'a', payload: null }])
assert.deepEqual(seen[0].viewer, { userId: 42 })
assert.equal(seen[0].idempotencyKey, 'key-1')
})
test('a step whose action has no progress() is not asked, and says nothing', async () => {
register([action(), action({ id: 'demo.zone.open', reversible: 'none', revert: undefined })])
steps = [step(1), step(2, 'demo.zone.open'), step(3, 'demo.uninstalled.thing')]
assert.deepEqual(await progress.forRun(RUN), [])
})
test('a module that throws, answers late or answers nonsense costs a line, never the page', async () => {
register([
action({
progress: async (env) => {
if (env.stepId === 1) throw new Error('sidecar down')
if (env.stepId === 2) return new Promise(() => {})
if (env.stepId === 3) return { label: 'Bad', left: -1, of: 2 }
return { label: 'Good', percent: 40 }
},
}),
])
steps = [step(1), step(2), step(3), step(4)]
const started = Date.now()
const lines = await progress.forRun(RUN)
assert.deepEqual(lines, [{ label: 'Good', percent: 40 }])
assert.ok(Date.now() - started < progress.PROGRESS_BUDGET_MS + 1500, 'the deadline held')
})
test('a database that fails is an empty list, not a rejection', async () => {
register([action({ progress: async () => ({ label: 'x', left: 1, of: 1 }) })])
stepsDb.listForRun = async () => {
throw new Error('pool closed')
}
assert.deepEqual(await progress.forRun(RUN), [])
})
test('one answer per run and reader within the window', async () => {
let asked = 0
register([
action({
progress: async () => {
asked++
return { label: 'Bandits', left: 3, of: 8 }
},
}),
])
steps = [step(1)]
let t = 1_000_000
const now = () => t
await progress.forRun(RUN, { now })
await progress.forRun(RUN, { now })
assert.equal(asked, 1, 'cached for the same reader')
await progress.forRun(RUN, { viewer: { userId: 5 }, now })
assert.equal(asked, 2, 'a different reader is asked for')
t += progress.CACHE_MS
await progress.forRun(RUN, { now })
assert.equal(asked, 3, 'asked again once the window passed')
})

View File

@@ -40,8 +40,9 @@ const NOW = new Date('2026-09-01T12:00:00Z')
const SPEC = {
schedule: { kind: 'manual' },
phases: [
{ id: 'muster', label: 'The muster', steps: [{ id: 's1', action: 'core.announce' }] },
{ id: 'assault', label: 'The assault', steps: [] },
// `key`, as spec.js validates and every stored spec has it (D314).
{ key: 'muster', label: 'The muster', steps: [{ id: 's1', action: 'core.announce' }] },
{ key: 'assault', label: 'The assault', steps: [] },
],
}
@@ -164,10 +165,32 @@ test('a calendar entry carries no operational field at all', async () => {
// The whole security property of this file, asserted positively: the entry has
// exactly these keys and gaining one is a deliberate act.
assert.deepEqual(Object.keys(entry).sort(), [
'kind', 'live', 'scheduledFor', 'seriesName', 'seriesSlug', 'slug', 'status', 'timezone', 'title',
'kind', 'live', 'runId', 'scheduledFor', 'seriesName', 'seriesSlug', 'slug', 'status', 'timezone',
'title',
])
})
test('a run entry names its run, and a projection names none', async () => {
// Rust phase 15, D125: a map marker carries core's run id, and the app finds
// the event it belongs to from this calendar. The id is the one the event page
// already publishes on each occurrence.
store.definitions[0].spec = {
...SPEC,
schedule: { kind: 'weekly', days: ['saturday'], time: '00:00' },
}
const result = await publicModel.calendar({ from: '2026-08-28', to: '2026-09-15', now: NOW })
const runs = result.entries.filter((e) => e.kind === 'run')
const projected = result.entries.filter((e) => e.kind === 'projected')
assert.equal(runs.length, 1)
assert.equal(runs[0].runId, store.runs[0].id)
assert.ok(projected.length > 0, 'the weekly schedule must forecast past the one run')
for (const entry of projected) assert.equal('runId' in entry, false)
const page = await publicModel.event('the-yew-invasion')
const occurrences = [page.event.current, page.event.next, ...page.event.upcoming, ...page.event.past]
assert.ok(occurrences.some((o) => o && o.runId === runs[0].runId))
})
test('the default window reaches back as well as forward', async () => {
// §I: this route is "upcoming, live and recent". The default used to start at
// `now`, which left no room for the third word — an event that finished an hour
@@ -321,6 +344,49 @@ test('a live run carries its phase LABEL, and never the spec behind it', async (
assert.equal(JSON.stringify(page).includes('core.announce'), false)
})
test('only the live occurrence carries progress, asked for the reader (1.12.0)', async () => {
const progress = require('../src/events/progress')
const original = progress.forRun
const asked = []
progress.forRun = async (run, { viewer }) => {
asked.push({ run: run.id, viewer })
return [{ label: 'Bandits', left: 3, of: 8 }]
}
try {
store.runs[0].status = 'running'
const page = await publicModel.event('the-yew-invasion', { userId: 42 })
assert.deepEqual(page.event.current.progress, [{ label: 'Bandits', left: 3, of: 8 }])
assert.deepEqual(asked, [{ run: 3692, viewer: { userId: 42 } }])
for (const o of [...page.event.upcoming, ...page.event.past]) assert.equal(o.progress, undefined)
store.runs[0].status = 'completed'
asked.length = 0
const done = await publicModel.event('the-yew-invasion')
assert.equal(done.event.current, null)
assert.equal(asked.length, 0, 'a finished run is not asked')
} finally {
progress.forRun = original
}
})
test('phaseLabel finds a phase by key first, still accepts id, and never shows a step', () => {
const { phaseLabel } = publicModel
// A UO event's shape: keyed phases, steps of UO's actions.
const uo = {
phases: [
{ key: 'gather', label: 'The gathering', steps: [{ action: 'uo.creature.spawn' }] },
{ key: 'siege', label: 'Siege of Yew', steps: [] },
],
}
assert.equal(phaseLabel(uo, 'gather'), 'The gathering')
assert.equal(phaseLabel(uo, 'siege'), 'Siege of Yew')
assert.equal(phaseLabel({ phases: [{ id: 'old', label: 'An older shape' }] }, 'old'), 'An older shape')
// A key and an id both matching: the key wins, because the key is what the engine writes.
assert.equal(phaseLabel({ phases: [{ id: 'x', label: 'By id' }, { key: 'x', label: 'By key' }] }, 'x'), 'By key')
assert.equal(phaseLabel(uo, 'nope'), null)
assert.equal(phaseLabel(uo, null), null)
})
test('a phase the pinned version does not name renders nothing rather than an id', async () => {
store.runs[0].status = 'running'
store.runs[0].current_phase = 'a-phase-since-renamed'

View File

@@ -30,7 +30,7 @@ const assert = require('node:assert/strict')
const registries = require('../src/modules/registries')
const runner = require('../src/utils/eventRunner')
const { classify } = require('../src/events/dispatch')
const { classify, MIN_RETRY_AFTER_MS, MAX_RETRY_AFTER_MS } = require('../src/events/dispatch')
const runsDb = require('../src/model/events/eventRuns.db')
const stepsDb = require('../src/model/events/eventRunSteps.db')
const logDb = require('../src/model/events/eventRunLog.db')
@@ -181,6 +181,10 @@ function installStubs() {
// sweep has its own file — answering with nothing is what keeps every `tick()`
// here measuring the runner rather than a teardown.
resourcesDb.runsNeedingCleanup = async () => []
// Its 1.11.0 sibling, which was never stubbed: a tick that reached the sweep
// with a terminal run in the store asked the dead pool and waited out its
// acquire timeout on every call.
resourcesDb.finishedRunsWithNothingLeft = async () => []
runsDb.setCleanupStatus = async (id, to, from = null) => {
const r = store.runs.get(id)
@@ -901,6 +905,113 @@ test('a transient failure retries on a flat backoff with the same idempotency ke
assert.equal(new Set(scripted['test.flaky'].calls.map((c) => c.idempotencyKey)).size, 1)
})
// ── §F: a failure's retryAfterMs (MODULE_API 1.15.0, Rust PLAN_REDESIGNS §14.3.13) ──
const retryLine = (id) => store.log.find((l) => l.runId === id && l.kind === 'step.retry')
test('retryAfterMs: the module says when, and the step waits that long instead of the flat delay', async () => {
register([scriptedAction('test.warming')])
scripted['test.warming'] = {
calls: [],
answers: [{ ok: false, retry: true, retryAfterMs: 10 * 60_000, error: 'not ready yet' }],
answer: { ok: true },
}
const id = seedRun([{ key: 'main', label: 'Main', steps: [step('test.warming', {}, 'skip')] }])
await runner.tick(T0)
assert.equal(stepsOf(id)[0].status, 'pending')
assert.equal(stepsOf(id)[0].due_at.getTime(), later(10 * 60_000).getTime())
assert.equal(retryLine(id).detail.retryAt, later(10 * 60_000).toISOString())
assert.equal(retryLine(id).detail.retryAfterMs, 10 * 60_000)
assert.equal(run(id).health, 'degraded', 'a hinted retry degrades the run as any retry does')
await runner.tick(later(runner.RETRY_MS))
assert.equal(scripted['test.warming'].calls.length, 1, 'the flat delay passing is not the hinted one')
await runner.tick(later(10 * 60_000))
assert.equal(scripted['test.warming'].calls.length, 2)
assert.equal(stepsOf(id)[0].status, 'done')
})
test('retryAfterMs: an unhinted retry line still says when', async () => {
register([scriptedAction('test.flaky')])
scripted['test.flaky'] = { calls: [], answer: { ok: false, retry: true, error: 'relay is down' } }
const id = seedRun([{ key: 'main', label: 'Main', steps: [step('test.flaky', {}, 'skip')] }])
await runner.tick(T0)
assert.equal(retryLine(id).detail.retryAt, later(runner.RETRY_MS).toISOString())
assert.equal('retryAfterMs' in retryLine(id).detail, false)
})
test('retryAfterMs: it is one attempt, so a module that never gets ready fails on schedule', async () => {
register([scriptedAction('test.warming')])
scripted['test.warming'] = {
calls: [],
answer: { ok: false, retry: true, retryAfterMs: 30 * 60_000, error: 'not ready yet' },
}
const id = seedRun([{ key: 'main', label: 'Main', steps: [step('test.warming', {}, 'skip')] }])
await runner.tick(T0)
await runner.tick(later(30 * 60_000))
assert.equal(stepsOf(id)[0].attempts, 2)
await runner.tick(later(60 * 60_000))
assert.equal(stepsOf(id)[0].attempts, runner.MAX_ATTEMPTS)
assert.equal(stepsOf(id)[0].status, 'failed', 'a hint changes when, never how many')
assert.equal(run(id).status, 'completed')
})
test('retryAfterMs: a run paused in the wait does not retry', async () => {
register([scriptedAction('test.warming')])
scripted['test.warming'] = {
calls: [],
answer: { ok: false, retry: true, retryAfterMs: 5 * 60_000, error: 'not ready yet' },
}
const id = seedRun([{ key: 'main', label: 'Main', steps: [step('test.warming', {}, 'skip')] }])
await runner.tick(T0)
await runsDb.transition(id, ['running'], 'paused', { clearClaim: true })
await runner.tick(later(6 * 60_000))
assert.equal(scripted['test.warming'].calls.length, 1, 'paused means nothing is dispatched')
assert.equal(stepsOf(id)[0].status, 'pending', 'the step is still there for a resume or a staff Retry')
})
test('retryAfterMs: a run cancelled in the wait does not retry', async () => {
register([scriptedAction('test.warming')])
scripted['test.warming'] = {
calls: [],
answer: { ok: false, retry: true, retryAfterMs: 5 * 60_000, error: 'not ready yet' },
}
const id = seedRun([{ key: 'main', label: 'Main', steps: [step('test.warming', {}, 'skip')] }])
await runner.tick(T0)
await runsDb.transition(id, ['running'], 'cancelled', { clearClaim: true })
await stepsDb.cancelPending(id)
await runner.tick(later(6 * 60_000))
assert.equal(scripted['test.warming'].calls.length, 1)
assert.equal(stepsOf(id)[0].status, 'cancelled')
})
test('classify: retryAfterMs is clamped to one minute–thirty minutes, and only on the retry shape', () => {
const at = (v) => classify({ ok: false, retry: true, retryAfterMs: v }, 'a').retryAfterMs
assert.equal(at(10 * 60_000), 10 * 60_000)
assert.equal(at(5_000), MIN_RETRY_AFTER_MS, 'too soon is the floor, not a refusal')
assert.equal(at(0), MIN_RETRY_AFTER_MS)
assert.equal(at(-1), MIN_RETRY_AFTER_MS)
assert.equal(at(5 * 60 * 60_000), MAX_RETRY_AFTER_MS, 'too late is the ceiling, not a refusal')
assert.equal(at(90_000.6), 90_001, 'whole milliseconds')
assert.equal(at(undefined), undefined, 'absent: the flat delay')
assert.equal(at(null), undefined)
assert.equal(at('600000'), undefined, 'a string is not a hint; the flat delay, and the failure is unchanged')
assert.equal(at(Number.NaN), undefined)
assert.equal(at(Infinity), undefined)
assert.equal(classify({ ok: false, retry: true, retryAfterMs: 'soon' }, 'a').outcome, 'retry')
assert.equal(classify({ ok: false, retryAfterMs: 120_000 }, 'a').retryAfterMs, 120_000, 'retry defaults on, so the hint is read')
const terminal = classify({ ok: false, retry: false, retryAfterMs: 120_000 }, 'a')
assert.equal(terminal.outcome, 'terminal')
assert.equal('retryAfterMs' in terminal, false, 'a terminal failure is never tried again, so a delay means nothing')
assert.equal('retryAfterMs' in classify({ ok: true, retryAfterMs: 120_000 }, 'a'), false)
})
test('on_failure: pause stops the run and the tick never picks it up again', async () => {
register([scriptedAction('test.bad'), scriptedAction('test.after')])
scripted['test.bad'] = { calls: [], answer: { ok: false, retry: false, error: 'the world is half changed' } }

View File

@@ -136,7 +136,8 @@ CREATE TABLE event_versions (
id INT AUTO_INCREMENT PRIMARY KEY,
definition_id INT NOT NULL,
version INT NOT NULL DEFAULT 1,
spec JSON NOT NULL
spec JSON NOT NULL,
verified_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE event_runs (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
@@ -149,11 +150,16 @@ CREATE TABLE event_runs (
health ENUM('ok','degraded','stalled') NOT NULL DEFAULT 'ok',
current_phase VARCHAR(64) NULL,
scheduled_for DATETIME NOT NULL,
timezone VARCHAR(64) NOT NULL DEFAULT 'UTC',
concurrency_key VARCHAR(190) NULL,
params JSON NULL,
rehearsal TINYINT(1) NOT NULL DEFAULT 0,
started_at DATETIME NULL,
ended_at DATETIME NULL,
claimed_by VARCHAR(64) NULL,
claim_expires_at DATETIME NULL,
started_by INT NULL,
origin JSON NULL,
last_error VARCHAR(500) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
@@ -250,6 +256,18 @@ CREATE TABLE event_action_settings (
updated_by INT NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE event_trigger_starts (
definition_id INT NOT NULL PRIMARY KEY,
claimed_at DATETIME NULL,
last_started_at DATETIME NULL,
last_run_id BIGINT NULL,
ignored_running INT NOT NULL DEFAULT 0,
ignored_cooldown INT NOT NULL DEFAULT 0,
ignored_unverified INT NOT NULL DEFAULT 0,
last_ignored_at DATETIME NULL,
last_ignored_reason VARCHAR(32) NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`
// The statements under test, verbatim from `eventRuns.db.js` and
@@ -1745,3 +1763,131 @@ test('setCleanupStatus is guarded, which is what stops a late row re-opening a s
assert.equal(await runsDb.setCleanupStatus(a.runId, 'pending', ['not_required']), false)
assert.equal(await runsDb.setCleanupStatus(a.runId, 'pending'), true)
})
// ── A trigger can start a run (Rust PLAN_REDESIGNS §14.3.12, D370) ─────────
//
// `eventStarts.test.js` proves what `starts.observe()` DECIDES against a stand-in
// whose claim keeps the rules. These prove the rules are what the server does:
// the JSON lookup over the published version, and the claim — one winner, the
// cooldown and the one-at-a-time check all inside one WHERE.
const definitionsDb = require('../src/model/events/eventDefinitions.db')
const triggerStartsDb = require('../src/model/events/eventTriggerStarts.db')
const startsOn = (on, extra = {}) => ({
schedule: { kind: 'manual' },
starts: [{ on, where: null, cooldown: '30m', dormant: false, ...extra }],
phases: [{ key: 'main', label: 'Main', steps: [] }],
})
test('findStartingOn reads the PUBLISHED version of ready definitions, and nothing else', async (t) => {
if (needDb(t)) return
const hit = await seedDefinition({ spec: startsOn('demo.bradley.destroyed') })
await seedDefinition({ state: 'draft', spec: startsOn('demo.bradley.destroyed') })
await seedDefinition({ state: 'archived', spec: startsOn('demo.bradley.destroyed') })
await seedDefinition({ spec: startsOn('demo.heli.downed') })
await seedDefinition({ spec: { schedule: { kind: 'manual' } } })
// Two starts, the trigger second: `$.starts[*].on` is every entry, not the first.
const second = await seedDefinition({
spec: { ...startsOn('demo.heli.downed'), starts: [{ on: 'demo.heli.downed' }, { on: 'demo.bradley.destroyed' }] },
})
await pool.query('UPDATE event_versions SET verified_at = ? WHERE id = ?', [T0, hit.versionId])
const found = await definitionsDb.findStartingOn('demo.bradley.destroyed')
assert.deepEqual(found.map((d) => Number(d.id)), [Number(hit.definitionId), Number(second.definitionId)])
assert.equal(found[0].version_spec.starts[0].on, 'demo.bradley.destroyed', 'the spec comes back parsed')
assert.ok(found[0].version_verified_at, 'and whether it may start unattended')
assert.equal(found[1].version_verified_at, null)
// A substring is not a trigger.
assert.equal((await definitionsDb.findStartingOn('demo.bradley')).length, 0)
})
test('two firings claiming at once: exactly one owns the start', async (t) => {
if (needDb(t)) return
const def = await seedDefinition({ spec: startsOn('demo.x', { cooldown: '0m' }) })
const results = await Promise.all(
Array.from({ length: 5 }, (_, i) =>
triggerStartsDb.claim(def.definitionId, { at: later(i * 1000), cooldownSeconds: 0, now: later(10_000) }),
),
)
assert.equal(results.filter(Boolean).length, 1)
})
test('the cooldown is measured from the last trigger-started run', async (t) => {
if (needDb(t)) return
const def = await seedDefinition({ spec: startsOn('demo.x') })
const id = def.definitionId
assert.equal(await triggerStartsDb.claim(id, { at: T0, cooldownSeconds: 1800, now: T0 }), true)
await triggerStartsDb.started(id, { at: T0, runId: 99 })
assert.equal(await triggerStartsDb.claim(id, { at: later(10 * 60_000), cooldownSeconds: 1800, now: later(10 * 60_000) }), false)
// Exactly at the boundary the cooldown has passed.
assert.equal(await triggerStartsDb.claim(id, { at: later(30 * 60_000), cooldownSeconds: 1800, now: later(30 * 60_000) }), true)
})
test('a going run blocks the claim; a future occurrence does not', async (t) => {
if (needDb(t)) return
const def = await seedDefinition({ spec: startsOn('demo.x', { cooldown: '0m' }) })
const id = def.definitionId
const run = await pool.query(
'INSERT INTO event_runs (definition_id, version_id, scope, status, scheduled_for) VALUES (?, ?, ?, ?, ?)',
[id, def.versionId, '', 'scheduled', later(24 * 60 * 60_000)],
)
assert.equal(await triggerStartsDb.isGoing(id, T0), false, 'tomorrow\'s occurrence is not going')
assert.equal(await triggerStartsDb.claim(id, { at: T0, cooldownSeconds: 0, now: T0 }), true)
await triggerStartsDb.release(id)
for (const [status, when] of [['running', T0], ['paused', T0], ['scheduled', later(-1000)]]) {
await pool.query('UPDATE event_runs SET status = ?, scheduled_for = ? WHERE id = ?', [status, when, run.insertId])
assert.equal(await triggerStartsDb.isGoing(id, T0), true, status)
assert.equal(await triggerStartsDb.claim(id, { at: T0, cooldownSeconds: 0, now: T0 }), false, status)
}
await pool.query("UPDATE event_runs SET status = 'completed' WHERE id = ?", [run.insertId])
assert.equal(await triggerStartsDb.claim(id, { at: T0, cooldownSeconds: 0, now: T0 }), true)
})
test('a claim held past a minute belongs to a dead process and can be taken', async (t) => {
if (needDb(t)) return
const def = await seedDefinition({ spec: startsOn('demo.x', { cooldown: '0m' }) })
const id = def.definitionId
assert.equal(await triggerStartsDb.claim(id, { at: T0, cooldownSeconds: 0, now: T0 }), true)
assert.equal(await triggerStartsDb.claim(id, { at: later(30_000), cooldownSeconds: 0, now: later(30_000) }), false)
assert.equal(await triggerStartsDb.claim(id, { at: later(61_000), cooldownSeconds: 0, now: later(61_000) }), true)
})
test('ignore counts by reason, and a start zeroes the counts', async (t) => {
if (needDb(t)) return
const def = await seedDefinition({ spec: startsOn('demo.x') })
const id = def.definitionId
await triggerStartsDb.ignore(id, 'running', T0)
await triggerStartsDb.ignore(id, 'running', T0)
await triggerStartsDb.ignore(id, 'cooldown', later(1000))
let row = await triggerStartsDb.forDefinition(id)
assert.equal(row.ignored_running, 2)
assert.equal(row.ignored_cooldown, 1)
assert.equal(row.last_ignored_reason, 'cooldown')
await assert.rejects(() => triggerStartsDb.ignore(id, 'bogus', T0), /unknown ignore reason/)
await triggerStartsDb.started(id, { at: later(2000), runId: 5 })
row = await triggerStartsDb.forDefinition(id)
assert.equal(row.ignored_running, 0)
assert.equal(Number(row.last_run_id), 5)
assert.equal(row.claimed_at, null)
})
test('a run carries its origin through the insert and back', async (t) => {
if (needDb(t)) return
const def = await seedDefinition()
const origin = { kind: 'trigger', triggerId: 'demo.x', variables: { grid: 'G8' } }
const runId = await runsDb.materialise({
definition_id: def.definitionId,
version_id: def.versionId,
scope: '',
scheduled_for: T0,
concurrency_key: null,
params: null,
started_by: null,
origin,
})
assert.deepEqual((await runsDb.getById(runId)).origin, origin)
})

View File

@@ -0,0 +1,371 @@
// ── Starting a run from a trigger (Rust PLAN_REDESIGNS §14.3.12, D370) ─────
//
// Two halves. The SPEC half: a definition's `starts` is validated the way a
// phase gate is (one grammar, one dormant rule), with a cooldown, and core's own
// `event.*` triggers refused. The EMIT half: `events/starts.observe()` decides
// whether a firing starts a run, and this file proves what it decides against an
// in-memory stand-in whose claim keeps the SQL's rules. The SQL itself — one
// winner, the cooldown and the one-at-a-time check in one WHERE — is proved
// against a real server in `eventRunnerSql.test.js`.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test, beforeEach, afterEach, after } = require('node:test')
const assert = require('node:assert/strict')
const registries = require('../src/modules/registries')
const spec = require('../src/events/spec')
const starts = require('../src/events/starts')
const definitionsDb = require('../src/model/events/eventDefinitions.db')
const startsDb = require('../src/model/events/eventTriggerStarts.db')
const runsModel = require('../src/model/events/eventRuns.model')
const db = require('../src/utils/db')
after(() => db.close())
const TRIGGER = 'demo.bradley.destroyed'
beforeEach(() => {
registries._reset()
registries.registerCore()
const api = registries.stage('demo')
api.registerEventTriggers([
{
id: TRIGGER,
label: 'Bradley destroyed',
ceiling: 'everyone',
variables: [
{ name: 'server', type: 'string', required: true, example: 'main', description: 'The server.' },
{ name: 'grid', type: 'string', required: false, example: 'G8', description: 'Where.' },
{ name: 'kills', type: 'int', required: false, example: 1, description: 'How many.' },
],
},
])
registries.apply(api.staged)
})
afterEach(() => registries._reset())
const withStarts = (startsValue) => ({
schedule: { kind: 'manual' },
starts: startsValue,
phases: [{ key: 'main', label: 'Main', steps: [] }],
})
// ── The spec half ──────────────────────────────────────────────────────────
test('a start is a gate\'s trigger and condition plus a cooldown, normalised', () => {
const result = spec.validate(
withStarts([{ on: TRIGGER, where: { variable: 'server', cmp: 'eq', value: 'main' }, cooldown: '120m' }]),
)
assert.equal(result.ok, true, JSON.stringify(result.errors))
assert.deepEqual(result.spec.starts, [
{ on: TRIGGER, where: { variable: 'server', cmp: 'eq', value: 'main' }, cooldown: '2h', dormant: false },
])
})
test('the cooldown defaults to thirty minutes, and zero is a real choice', () => {
const a = spec.validate(withStarts([{ on: TRIGGER }]))
assert.equal(a.spec.starts[0].cooldown, '30m')
assert.equal(a.spec.starts[0].where, null)
const b = spec.validate(withStarts([{ on: TRIGGER, cooldown: 0 }]))
assert.equal(b.spec.starts[0].cooldown, '0m')
assert.equal(spec.parseCooldown('0m'), 0)
})
test('a cooldown past seven days, or not a duration, is refused by name', () => {
for (const cooldown of ['8d', '1h30m', 'soon', -5]) {
const result = spec.validate(withStarts([{ on: TRIGGER, cooldown }]))
assert.equal(result.ok, false, String(cooldown))
assert.match(result.errors[0], /^spec\.starts\[0\]\.cooldown:/)
}
assert.equal(spec.validate(withStarts([{ on: TRIGGER, cooldown: '7d' }])).ok, true)
})
test('core\'s own event.* triggers cannot start a run', () => {
const result = spec.validate(withStarts([{ on: 'event.run.started' }]))
assert.equal(result.ok, false)
assert.match(result.errors[0], /event system's own triggers/)
})
test('the condition is checked against the trigger\'s declaration, path and all', () => {
const result = spec.validate(withStarts([{ on: TRIGGER, where: { variable: 'sever', cmp: 'eq', value: 'main' } }]))
assert.equal(result.ok, false)
assert.ok(result.errors.some((e) => e.startsWith('spec.starts[0].where') && e.includes('sever')), result.errors.join('\n'))
})
test('a start on a trigger nobody registers saves dormant and refuses to publish', () => {
const result = spec.validate(withStarts([{ on: 'gone.trigger', where: { variable: 'x', cmp: 'eq', value: 1 } }]))
assert.equal(result.ok, true)
assert.equal(result.spec.starts[0].dormant, true)
assert.deepEqual(result.spec.starts[0].where, { variable: 'x', cmp: 'eq', value: 1 }, 'kept, not dropped')
assert.deepEqual(spec.publishable(result.spec), { ok: false, dormant: ['gone.trigger'] })
})
test('validate accepts its own output, and an empty list is not written', () => {
const first = spec.validate(withStarts([{ on: TRIGGER, cooldown: '45m' }]))
const second = spec.validate(first.spec)
assert.deepEqual(second.spec, first.spec)
assert.equal('starts' in spec.validate(withStarts([])).spec, false)
})
test('bad shapes: not a list, too many, unknown keys', () => {
assert.match(spec.validate(withStarts({ on: TRIGGER })).errors[0], /spec\.starts: expected an array/)
const many = Array.from({ length: spec.MAX_STARTS + 1 }, () => ({ on: TRIGGER }))
assert.match(spec.validate(withStarts(many)).errors[0], /at most/)
assert.match(spec.validate(withStarts([{ on: TRIGGER, count: 2 }])).errors[0], /unknown key\(s\) count/)
})
// ── The emit half ──────────────────────────────────────────────────────────
const T0 = new Date('2026-10-16T20:00:00Z')
let store
const originals = {
definitionsDb: { ...definitionsDb },
startsDb: { ...startsDb },
runsModel: { ...runsModel },
}
// A run counts as going while it is not terminal — the SQL's own reading, with
// "scheduled and due" folded in because a trigger-started run is due at once.
const GOING = ['scheduled', 'starting', 'running', 'paused', 'ending']
function installStubs({ definitions }) {
store = { definitions, runs: [], state: new Map(), creates: [], nextRun: 1 }
definitionsDb.findStartingOn = async (triggerId) =>
store.definitions.filter((d) => (d.version_spec.starts || []).some((s) => s.on === triggerId))
const stateOf = (id) => {
if (!store.state.has(id)) {
store.state.set(id, {
claimed_at: null,
last_started_at: null,
last_run_id: null,
ignored_running: 0,
ignored_cooldown: 0,
ignored_unverified: 0,
last_ignored_reason: null,
})
}
return store.state.get(id)
}
const going = (id) => store.runs.some((r) => r.definition_id === id && GOING.includes(r.status))
startsDb.forDefinition = async (id) => store.state.get(id) || null
startsDb.isGoing = async (id) => going(id)
startsDb.claim = async (id, { at, cooldownSeconds, now }) => {
const s = stateOf(id)
if (s.claimed_at && now - s.claimed_at < startsDb.CLAIM_STALE_MS) return false
if (s.last_started_at && s.last_started_at > new Date(at.getTime() - cooldownSeconds * 1000)) return false
if (going(id)) return false
s.claimed_at = now
return true
}
startsDb.started = async (id, { at, runId }) => {
Object.assign(stateOf(id), {
claimed_at: null,
last_started_at: at,
last_run_id: runId,
ignored_running: 0,
ignored_cooldown: 0,
ignored_unverified: 0,
})
}
startsDb.release = async (id) => {
stateOf(id).claimed_at = null
}
startsDb.ignore = async (id, reason) => {
const s = stateOf(id)
s[`ignored_${reason}`] += 1
s.last_ignored_reason = reason
}
runsModel.create = async (definitionId, opts, userId) => {
store.creates.push({ definitionId, opts, userId })
const def = store.definitions.find((d) => d.id === definitionId)
if (!def.version_verified_at) return { ok: false, code: 'unverified', errors: ['unverified'] }
const existing = store.runs.find(
(r) => r.definition_id === definitionId && r.scheduled_for.getTime() === opts.scheduledFor.getTime(),
)
if (existing) return { ok: true, created: false, run: existing }
const run = { id: store.nextRun++, definition_id: definitionId, status: 'scheduled', scheduled_for: opts.scheduledFor, origin: opts.origin }
store.runs.push(run)
return { ok: true, created: true, run }
}
}
afterEach(() => {
Object.assign(definitionsDb, originals.definitionsDb)
Object.assign(startsDb, originals.startsDb)
Object.assign(runsModel, originals.runsModel)
})
const definition = (over = {}) => ({
id: 7,
title: 'Launch Site Lockdown',
grace_seconds: 900,
version_verified_at: new Date('2026-10-01T00:00:00Z'),
version_spec: {
schedule: { kind: 'manual' },
starts: [{ on: TRIGGER, where: { variable: 'server', cmp: 'eq', value: 'main' }, cooldown: '30m', dormant: false }],
phases: [{ key: 'main', label: 'Main', steps: [] }],
},
...over,
})
const firing = (at, data = { server: 'main', grid: 'G8' }, extra = {}) => ({
triggerId: TRIGGER,
occurredAt: at.toISOString(),
subject: 'bradley-1',
data,
...extra,
})
const plus = (ms) => new Date(T0.getTime() + ms)
test('a matching firing starts one run, now, with its origin', async () => {
installStubs({ definitions: [definition()] })
const summary = await starts.observe(firing(T0, { server: 'main', grid: 'G8', stray: 'x' }), { now: plus(2_000) })
assert.deepEqual(summary, { definitions: 1, started: 1, ignored: 0 })
assert.equal(store.runs.length, 1)
const [{ opts, userId }] = store.creates
assert.equal(userId, null, 'no user started it')
assert.equal(opts.source, 'trigger')
assert.equal(opts.scheduledFor.toISOString(), T0.toISOString(), 'the firing\'s time, not the observer\'s')
assert.deepEqual(opts.origin, {
kind: 'trigger',
triggerId: TRIGGER,
label: 'Bradley destroyed',
occurredAt: T0.toISOString(),
subject: 'bradley-1',
matched: 'server is "main"',
// Declared variables only: `stray` is not something the trigger declares.
variables: { server: 'main', grid: 'G8' },
})
assert.equal(store.state.get(7).last_run_id, 1)
})
test('a firing that does not match the condition starts nothing and counts nothing', async () => {
installStubs({ definitions: [definition()] })
const summary = await starts.observe(firing(T0, { server: 'staging' }), { now: plus(1_000) })
assert.deepEqual(summary, { definitions: 1, started: 0, ignored: 0 })
assert.equal(store.creates.length, 0)
assert.equal(store.state.has(7), false)
})
test('a second firing while the run is going starts nothing, and is counted as running', async () => {
installStubs({ definitions: [definition({ version_spec: { ...definition().version_spec, starts: [{ ...definition().version_spec.starts[0], cooldown: '0m' }] } })] })
await starts.observe(firing(T0), { now: plus(1_000) })
const summary = await starts.observe(firing(plus(30_000)), { now: plus(31_000) })
assert.deepEqual(summary, { definitions: 1, started: 0, ignored: 1 })
assert.equal(store.runs.length, 1)
assert.equal(store.state.get(7).ignored_running, 1)
})
test('inside the cooldown, a firing starts nothing and is counted; after it, a second run', async () => {
installStubs({ definitions: [definition()] })
await starts.observe(firing(T0), { now: plus(1_000) })
store.runs[0].status = 'completed'
await starts.observe(firing(plus(10 * 60_000)), { now: plus(10 * 60_000) })
assert.equal(store.runs.length, 1)
assert.equal(store.state.get(7).ignored_cooldown, 1)
const summary = await starts.observe(firing(plus(31 * 60_000)), { now: plus(31 * 60_000) })
assert.equal(summary.started, 1)
assert.equal(store.runs.length, 2)
assert.equal(store.state.get(7).ignored_cooldown, 0, 'a new start zeroes the counts')
})
test('one firing reported twice is one run, and the repeat is not counted', async () => {
installStubs({ definitions: [definition()] })
await starts.observe(firing(T0), { now: plus(1_000) })
const summary = await starts.observe(firing(T0), { now: plus(1_500) })
assert.equal(summary.started, 0)
assert.equal(summary.ignored, 0)
assert.equal(store.runs.length, 1)
assert.equal(store.state.get(7).ignored_running, 0)
})
test('an unverified version is not started by a trigger, and is counted', async () => {
installStubs({ definitions: [definition({ version_verified_at: null })] })
const summary = await starts.observe(firing(T0), { now: plus(1_000) })
assert.deepEqual(summary, { definitions: 1, started: 0, ignored: 1 })
assert.equal(store.creates.length, 0, 'not even tried')
assert.equal(store.state.get(7).ignored_unverified, 1)
})
test('a firing older than the grace window starts nothing', async () => {
installStubs({ definitions: [definition({ grace_seconds: 60 })] })
const summary = await starts.observe(firing(T0), { now: plus(5 * 60_000) })
assert.equal(summary.started, 0)
assert.equal(store.creates.length, 0)
})
test('a firing stamped in the future starts the run now, not later', async () => {
installStubs({ definitions: [definition()] })
await starts.observe(firing(plus(60 * 60_000)), { now: plus(1_000) })
assert.equal(store.creates[0].opts.scheduledFor.toISOString(), plus(1_000).toISOString())
})
test('core\'s event.* triggers are never looked up, and a dormant start never fires', async () => {
installStubs({ definitions: [] })
let asked = 0
definitionsDb.findStartingOn = async () => {
asked += 1
return []
}
await starts.observe({ triggerId: 'event.run.started', data: {} })
assert.equal(asked, 0)
installStubs({
definitions: [definition({ version_spec: { ...definition().version_spec, starts: [{ on: TRIGGER, where: null, cooldown: '30m', dormant: true }] } })],
})
const summary = await starts.observe(firing(T0), { now: plus(1_000) })
assert.equal(summary.started, 0)
})
test('two definitions on one trigger each decide for themselves', async () => {
const other = definition({ id: 8, title: 'Other', version_spec: { ...definition().version_spec, starts: [{ on: TRIGGER, where: null, cooldown: '30m', dormant: false }] } })
installStubs({ definitions: [definition(), other] })
const summary = await starts.observe(firing(T0, { server: 'staging' }), { now: plus(1_000) })
assert.deepEqual(summary, { definitions: 2, started: 1, ignored: 0 })
assert.equal(store.runs[0].definition_id, 8)
})
test('a create that throws gives the claim back and is not fatal to the others', async () => {
const other = definition({ id: 8 })
installStubs({ definitions: [definition(), other] })
const create = runsModel.create
runsModel.create = async (id, ...rest) => {
if (id === 7) throw new Error('boom')
return create(id, ...rest)
}
const summary = await starts.observe(firing(T0), { now: plus(1_000) })
assert.equal(summary.started, 1)
assert.equal(store.state.get(7).claimed_at, null)
})
test('an oversized payload keeps only the variables the condition named', () => {
const big = 'x'.repeat(starts.MAX_ORIGIN_BYTES)
const origin = starts.originOf(
{ triggerId: TRIGGER, data: { server: 'main', grid: big } },
registries.eventTrigger(TRIGGER),
{ where: { variable: 'server', cmp: 'eq', value: 'main' } },
T0,
)
assert.deepEqual(origin.variables, { server: 'main', _truncated: true })
})
test('the editor\'s state line, and its absence', () => {
assert.equal(starts.describeState(null), null)
assert.deepEqual(
starts.describeState({ last_started_at: T0, last_run_id: 4, ignored_running: 2, ignored_cooldown: 1, ignored_unverified: 0 }),
{
lastStartedAt: T0,
lastRunId: 4,
ignoredRunning: 2,
ignoredCooldown: 1,
ignoredUnverified: 0,
lastIgnoredAt: null,
lastIgnoredReason: null,
},
)
})

View File

@@ -0,0 +1,302 @@
// ── The step editor's contract additions (MODULE_API 1.13.0) ───────────────
//
// Rust PLAN_REDESIGNS §2: event templates (D192), a param's `duration`, a lease's
// `example` and an option row's `note`. Proved the way eventModuleContract.test.js
// proves the rest of the seam — a real module in a real directory, scanned and
// registered by the real loader — because a test that staged by hand would pass
// against a loader that forwards none of it.
//
// The pool points at a closed port before anything is required. `draftAhead`
// reads a version, and that read is stubbed on the module object the model holds.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const fs = require('fs')
const os = require('os')
const path = require('path')
const { test, beforeEach, after } = require('node:test')
const assert = require('node:assert/strict')
const express = require('express')
const db = require('../src/utils/db')
const registries = require('../src/modules/registries')
const definitions = require('../src/model/events/eventDefinitions.model')
const versionsDb = require('../src/model/events/eventVersions.db')
after(() => db.close())
let tmpRoot
const emptyTiers = () => ({
public: express.Router(),
admin: express.Router(),
player: express.Router(),
})
function loadModule(id, source, manifest = {}) {
const dir = path.join(tmpRoot, id)
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(
path.join(dir, 'module.json'),
JSON.stringify({ id, name: id, version: '1.0.0', coreApi: '^1.13.0', server: 'index.js', ...manifest }),
)
fs.writeFileSync(path.join(dir, 'index.js'), source)
// A test that loads twice rewrites the same file, and require() would hand the
// loader the first one back.
delete require.cache[path.join(dir, 'index.js')]
process.env.MODULES_DIR = tmpRoot
registries._reset()
delete require.cache[require.resolve('../src/modules/loader')]
// eslint-disable-next-line global-require
const loader = require('../src/modules/loader')
loader.load(emptyTiers())
return loader.list().find((m) => m.id === id)
}
const assertRegistered = (record) => {
assert.equal(record.state, 'registered', record.reason || 'expected the module to register')
}
const assertFailed = (record, pattern) => {
assert.notEqual(record.state, 'registered', 'expected the module to be refused')
assert.match(record.reason || '', pattern)
}
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rg-step-editor-'))
})
// A template whose build() answers whatever the module's `mode` input says, so
// one registration covers every path build() can take.
const TEMPLATE_MODULE = `module.exports = (ctx, api) => {
api.registerEventTemplates([{
id: 'demo.template.weekend',
label: 'Weekend',
description: 'Two days of something.',
inputs: [
{ name: 'what', type: 'string', required: true, example: 'double gather' },
{ name: 'minutes', type: 'int', required: true, example: 60, duration: 'minutes' },
{ name: 'mode', type: 'string', required: false, example: 'ok' },
],
async build({ inputs }) {
if (inputs.mode === 'refuse') return { ok: false, error: 'that is not a weekend' }
if (inputs.mode === 'throw') throw new Error('database exploded at row 7')
if (inputs.mode === 'nothing') return null
if (inputs.mode === 'bad') return { title: 'Bad', spec: { phases: [{ key: 'Not A Key', steps: [] }] } }
return {
title: 'Weekend: ' + inputs.what,
summary: 'For ' + inputs.minutes + ' minutes.',
spec: {
phases: [{
key: 'hold',
label: 'Hold',
advance: { after: inputs.minutes + 'm' },
steps: [{ actionId: 'core.wait', params: { seconds: 5 } }],
}],
},
}
},
}])
}`
// ── Templates ─────────────────────────────────────────────────────────────
test('a module registers a template, and the catalog lists it without build()', () => {
assertRegistered(loadModule('demo', TEMPLATE_MODULE))
const [t] = registries.allEventTemplates()
assert.equal(t.id, 'demo.template.weekend')
assert.equal(t.owner, 'demo')
assert.equal(t.build, undefined)
// The inputs are params, checked by the same function: the duration survives.
assert.deepEqual(t.inputs.map((p) => [p.name, p.type, p.required, p.duration || null]), [
['what', 'string', true, null],
['minutes', 'int', true, 'minutes'],
['mode', 'string', false, null],
])
assert.equal(typeof registries.eventTemplate('demo.template.weekend').build, 'function')
})
test('a template outside its module\'s prefix, without build(), or asking too much is refused', () => {
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventTemplates([{ id: 'other.template.x', label: 'X', build() { return {} } }])
}`), /not namespaced "demo\."/)
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventTemplates([{ id: 'demo.template.x', label: 'X' }])
}`), /has no build\(\)/)
const nine = Array.from({ length: 9 }, (_, i) => `{ name: 'p${i}', type: 'string', example: 'x' }`).join(',')
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventTemplates([{ id: 'demo.template.x', label: 'X', inputs: [${nine}], build() { return {} } }])
}`), /asks for 9 inputs/)
// An input is a param, so it needs an example like every param does.
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventTemplates([{ id: 'demo.template.x', label: 'X', inputs: [{ name: 'a', type: 'string' }], build() { return {} } }])
}`), /registerEventTemplates: demo\.template\.x: param "a" needs an example/)
})
test('a filled-in template is a draft: validated, normalised, and saved nowhere', async () => {
assertRegistered(loadModule('demo', TEMPLATE_MODULE))
registries.registerCore()
const result = await definitions.buildFromTemplate('demo.template.weekend', { what: 'wood', minutes: 90 })
assert.equal(result.ok, true, JSON.stringify(result.errors))
assert.equal(result.draft.title, 'Weekend: wood')
assert.equal(result.draft.summary, 'For 90 minutes.')
assert.equal(result.draft.spec.phases[0].advance.after, '90m')
assert.equal(result.draft.spec.phases[0].steps[0].actionId, 'core.wait')
})
test('the inputs are checked before build() is called, in the author\'s words', async () => {
assertRegistered(loadModule('demo', TEMPLATE_MODULE))
registries.registerCore()
const missing = await definitions.buildFromTemplate('demo.template.weekend', { minutes: 10 })
assert.equal(missing.ok, false)
assert.equal(missing.status, 400)
assert.deepEqual(missing.errors, ['"what" is required'])
const extra = await definitions.buildFromTemplate('demo.template.weekend', { what: 'x', minutes: 10, colour: 'red' })
assert.equal(extra.ok, false)
assert.match(extra.errors[0], /"colour" is not a param of demo\.template\.weekend/)
const unknown = await definitions.buildFromTemplate('demo.template.nope', {})
assert.equal(unknown.status, 404)
})
test('every way build() can fail is an answer, and only a refusal reaches the author verbatim', async () => {
assertRegistered(loadModule('demo', TEMPLATE_MODULE))
registries.registerCore()
const base = { what: 'x', minutes: 10 }
const refused = await definitions.buildFromTemplate('demo.template.weekend', { ...base, mode: 'refuse' })
assert.equal(refused.status, 400)
assert.deepEqual(refused.errors, ['that is not a weekend'])
// A throw is logged, not shown: the module's internals are not the author's.
const threw = await definitions.buildFromTemplate('demo.template.weekend', { ...base, mode: 'throw' })
assert.equal(threw.status, 502)
assert.doesNotMatch(threw.errors.join(' '), /database exploded/)
assert.match(threw.errors[0], /"Weekend" could not be filled in/)
const nothing = await definitions.buildFromTemplate('demo.template.weekend', { ...base, mode: 'nothing' })
assert.equal(nothing.status, 502)
const bad = await definitions.buildFromTemplate('demo.template.weekend', { ...base, mode: 'bad' })
assert.equal(bad.status, 502)
assert.match(bad.errors[0], /made a plan core cannot accept/)
assert.ok(bad.errors.length > 1, 'the spec errors ride along for whoever reads the response')
})
// ── A param's duration ────────────────────────────────────────────────────
test('a duration is minutes, on a number, and the catalog carries it', () => {
assertRegistered(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventActions([{
id: 'demo.hold', label: 'Hold', risk: 'notify', reversible: 'none', version: 1,
params: [{ name: 'minutes', type: 'int', required: true, example: 5, duration: 'minutes' }],
async perform() { return { ok: true } },
}])
}`))
assert.equal(registries.eventAction('demo.hold').params[0].duration, 'minutes')
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventActions([{
id: 'demo.hold', label: 'Hold', risk: 'notify', reversible: 'none', version: 1,
params: [{ name: 'for', type: 'string', example: '5m', duration: 'minutes' }],
async perform() { return { ok: true } },
}])
}`), /is a duration and must be int or float/)
assertFailed(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventActions([{
id: 'demo.hold', label: 'Hold', risk: 'notify', reversible: 'none', version: 1,
params: [{ name: 'hours', type: 'int', example: 2, duration: 'hours' }],
async perform() { return { ok: true } },
}])
}`), /has duration "hours"; the one unit is minutes/)
})
test('core.lease\'s minutes is a duration, and its examples name no game', () => {
registries._reset()
registries.registerCore()
const lease = registries.eventAction('core.lease')
assert.equal(lease.params.find((p) => p.name === 'minutes').duration, 'minutes')
// The params without a duration do not grow the key at all.
assert.equal('duration' in lease.params.find((p) => p.name === 'value'), false)
const words = registries.allEventActions()
.filter((a) => a.owner === 'core')
.flatMap((a) => a.params.map((p) => String(p.example)))
.join(' ')
assert.doesNotMatch(words, /\buo\.|Britain|Cove|skillgain/)
})
// ── A lease's example ─────────────────────────────────────────────────────
const leaseModule = (example) => `module.exports = (ctx, api) => {
api.registerEventLeases([{
id: 'demo.flag', label: 'Flag', type: 'bool', maxDurationMs: 3600000,
${example === undefined ? '' : `example: ${example},`}
async read() { return { ok: true, value: false } },
async apply() { return { ok: true } },
async restore() { return { ok: true } },
}])
}`
test('a lease may carry an example for its value, and it is served', () => {
assertRegistered(loadModule('demo', leaseModule('true')))
assert.equal(registries.allEventLeases()[0].example, true)
assertRegistered(loadModule('demo', leaseModule(undefined)))
assert.equal(registries.allEventLeases()[0].example, null)
assertFailed(loadModule('demo', leaseModule('{ on: true }')), /example must be a single value/)
})
// ── An option's note ──────────────────────────────────────────────────────
test('an option may carry a note, kept as text and bounded', async () => {
assertRegistered(loadModule('demo', `module.exports = (ctx, api) => {
api.registerEventOptionSources([{
id: 'demo.options.kits', label: 'Kits',
async resolve() {
return [
{ value: 'vip', label: 'VIP', note: '9 of 41 linked players have used it up' },
{ value: 'long', note: 'x'.repeat(500) },
{ value: 'plain' },
]
},
}])
}`))
const answer = await registries.resolveOptionSource('demo.options.kits')
assert.equal(answer.options[0].note, '9 of 41 linked players have used it up')
assert.equal(answer.options[1].note.length, 300)
assert.equal('note' in answer.options[2], false)
})
// ── The draft ahead of its published version ──────────────────────────────
test('draftAhead compares the working copy with the published spec as data', async (t) => {
const published = { phases: [{ key: 'a', steps: [{ actionId: 'core.wait', params: { seconds: 5 } }] }] }
const original = versionsDb.getById
t.after(() => { versionsDb.getById = original })
versionsDb.getById = async (id) => (id === 7 ? { id: 7, spec: published } : null)
// Never published: nothing to be ahead of.
assert.equal(await definitions.draftAhead({ current_version_id: null, spec: published }), false)
// The same plan with its keys in another order is not an edit.
const reordered = { phases: [{ steps: [{ params: { seconds: 5 }, actionId: 'core.wait' }], key: 'a' }] }
assert.equal(await definitions.draftAhead({ current_version_id: 7, spec: reordered }), false)
const edited = { phases: [{ key: 'a', steps: [{ actionId: 'core.wait', params: { seconds: 6 } }] }] }
assert.equal(await definitions.draftAhead({ current_version_id: 7, spec: edited }), true)
// A version that cannot be found answers false rather than asking the author
// to choose between two plans one of which is missing.
assert.equal(await definitions.draftAhead({ current_version_id: 8, spec: edited }), false)
})

View File

@@ -52,6 +52,9 @@ const resourcesDb = require('../src/model/events/eventRunResources.db')
const participantsDb = require('../src/model/events/eventRunParticipants.db')
const seriesDb = require('../src/model/events/eventSeries.db')
const gatesDb = require('../src/model/events/eventPhaseGates.db')
// Rust PLAN_REDESIGNS §14.3.12: the editor's shape reads the trigger-start state.
// The same rule as every leg above, a fifth time.
const triggerStartsDb = require('../src/model/events/eventTriggerStarts.db')
const activity = require('../src/model/activity/activity.model')
const db = require('../src/utils/db')
@@ -69,6 +72,7 @@ for (const [name, mod] of [
['logDb', logDb],
['seriesDb', seriesDb],
['gatesDb', gatesDb],
['triggerStartsDb', triggerStartsDb],
['settingsDb', settingsDb],
['budgetDb', budgetDb],
['resourcesDb', resourcesDb],
@@ -96,6 +100,7 @@ function installStubs() {
log: [],
series: new Map(),
gates: [],
triggerStarts: new Map(),
settings: new Map(),
budget: new Map(),
resources: [],
@@ -295,6 +300,7 @@ function installStubs() {
// it merely made the file slow. Worth the comment: when the runner or a model
// gains a leg, every file that stubs the layer under it needs the stub.
gatesDb.listForRun = async (runId) => store.gates.filter((g) => g.run_id === runId)
triggerStartsDb.forDefinition = async (id) => store.triggerStarts.get(id) || null
logDb.listForRun = async (runId) => store.log.filter((l) => l.run_id === runId).reverse()
logDb.write = async ({ runId, stepId = null, kind, phase = null, detail = null }) => {

View File

@@ -395,6 +395,79 @@ test('a failed upgrade leaves the previous version in place', async () => {
assert.deepEqual(fs.readdirSync(tmpRoot), ['uo'])
})
// ── One module per site ────────────────────────────────────────────────────
/** A second, different module's manifest and artifact, served beside the first. */
function otherModuleRoutes(id = 'rust') {
const tarball = bundle({ id })
const artifact = `https://releases.example.com/mod/${id}-1.0.0.tar.gz`
const url = `https://releases.example.com/mod/${id}-1.0.0.json`
return {
url,
routes: {
[url]: manifestFor(tarball, { id, name: id, artifact: `${id}-1.0.0.tar.gz`, url: artifact }),
[artifact]: tarball,
},
artifact,
}
}
test('a second, different module is refused before anything is downloaded', async () => {
const first = goodRoutes()
await install.install({ url: MANIFEST_URL, hosts: HOSTS, fetchImpl: fakeFetch(first.routes) })
const other = otherModuleRoutes('rust')
const fetchImpl = fakeFetch(other.routes)
await assert.rejects(
() => install.install({ url: other.url, hosts: HOSTS, fetchImpl }),
(err) => {
assert.equal(err.name, 'InstallError')
// 409: nothing is wrong with the URL; the SITE is not in a state to take it.
assert.equal(err.status, 409)
assert.match(err.message, /already runs the module "uo"/)
assert.match(err.message, /remove it before installing "rust"/)
return true
},
)
// Refused on the manifest alone: the artifact was never fetched, and the
// volume holds exactly what it held before.
assert.ok(!fetchImpl.seen.includes(other.artifact), 'the artifact was not downloaded')
assert.deepEqual(fs.readdirSync(tmpRoot), ['uo'])
})
test('the same module is still an upgrade, and removing it frees the site for another', async () => {
const first = goodRoutes()
await install.install({ url: MANIFEST_URL, hosts: HOSTS, fetchImpl: fakeFetch(first.routes) })
// An upgrade of what is installed is exactly what the rule allows.
const second = goodRoutes({ version: '2.0.0', manifest: { version: '2.0.0' } })
second.routes[MANIFEST_URL] = manifestFor(second.tarball, { version: '2.0.0' })
const upgraded = await install.install({ url: MANIFEST_URL, hosts: HOSTS, fetchImpl: fakeFetch(second.routes) })
assert.equal(upgraded.replaced, true)
// And once it is gone, the site takes a different one.
await install.removeDir('uo')
const other = otherModuleRoutes('rust')
const result = await install.install({ url: other.url, hosts: HOSTS, fetchImpl: fakeFetch(other.routes) })
assert.equal(result.id, 'rust')
assert.deepEqual(install.installedIds(), ['rust'])
})
test('what counts as installed is what the loader would scan', () => {
// A real module, an install's scratch directory, a swap's aside copy and a
// directory with no module.json. Only the first is a module.
fs.mkdirSync(path.join(tmpRoot, 'uo'))
fs.writeFileSync(path.join(tmpRoot, 'uo', 'module.json'), '{}')
fs.mkdirSync(path.join(tmpRoot, '.install-rust-abc'))
fs.writeFileSync(path.join(tmpRoot, '.install-rust-abc', 'module.json'), '{}')
fs.mkdirSync(path.join(tmpRoot, 'uo.replaced-123'))
fs.writeFileSync(path.join(tmpRoot, 'uo.replaced-123', 'module.json'), '{}')
fs.mkdirSync(path.join(tmpRoot, 'notes'))
assert.deepEqual(install.installedIds(), ['uo'])
})
// ── The volume ─────────────────────────────────────────────────────────────
test('moduleDir refuses an id that is not one', () => {

View File

@@ -495,6 +495,7 @@ test('ctx exposes exactly the documented surface, and is frozen', () => {
fs.writeFileSync(${JSON.stringify(seen)}, JSON.stringify({
keys: Object.keys(ctx).sort(),
middleware: Object.keys(ctx.middleware).sort(),
events: Object.keys(ctx.events).sort(),
moduleId: ctx.moduleId,
mutable,
}))
@@ -530,10 +531,42 @@ test('ctx exposes exactly the documented surface, and is frozen', () => {
assert.deepEqual(probe.middleware, [
'accountChangeLimiter', 'noindex', 'rateLimit', 'requireAuth', 'requireRole', 'siteMode', 'validate',
])
// API 1.10.0 gave `events` its `reconcile`, and 1.11.0 its `expired` (Rust
// PLAN_FIXES D183): the game ended a ledgered resource at its own deadline.
assert.deepEqual(probe.events, ['emit', 'expired', 'reconcile'])
assert.equal(probe.moduleId, 'probe')
assert.equal(probe.mutable, false, 'ctx members must be frozen')
})
test("ctx.events.expired closes the calling module's rows, whatever it passes", async () => {
// The owner is bound by the loader, never read from the arguments — the same
// rule `reconcile` keeps. Without it a module could mark another module's
// resources expired and take them off the teardown list.
const cleanup = require('../src/events/cleanup')
const original = cleanup.expireResource
const calls = []
cleanup.expireResource = async (owner, resource) => {
calls.push({ owner, resource })
return { expired: 1 }
}
try {
writeModule('zoner', {
server: `module.exports = (ctx) => {
const result = ctx.events.expired({ kind: 'zone', ref: '3:rg-1', owner: 'someone-else', owner_module: 'x' })
if (result !== undefined) throw new Error('expired must return undefined')
}`,
})
assert.equal(stateOf(freshLoader(tmpRoot), 'zoner').state, 'registered')
await new Promise((resolve) => setImmediate(resolve))
assert.equal(calls.length, 1)
assert.equal(calls[0].owner, 'zoner')
assert.equal(calls[0].resource.kind, 'zone')
assert.equal(calls[0].resource.ref, '3:rg-1')
} finally {
cleanup.expireResource = original
}
})
// ── Lifecycle hooks ────────────────────────────────────────────────────────
test('a lifecycle hook must be a function, and may be registered once', () => {