25 Commits

Author SHA1 Message Date
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
49 changed files with 3676 additions and 121 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 || '',
@@ -545,7 +547,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 +558,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 +636,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 +966,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,8 +1001,12 @@ 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}` : ''}`

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>

View File

@@ -22,11 +22,21 @@ import {
paramsMode,
paramValue,
setParam,
setParamList,
listValue,
addToList,
filterOptions,
datetimeInputValue,
priceBodyFrom,
worthPricing,
boolValue,
isSegmentable,
noteFor,
missingParams,
guardedAdvance,
shortfallSentence,
} from '../../../lib/eventAuthoring.js'
import { operatorsForType } from '../../../lib/engagementRules.js'
import { operatorsForType, coerceLiteral } from '../../../lib/engagementRules.js'
// Admin → Events → the definition editor (EVENTS.md §I, Phase 3).
//
@@ -215,7 +225,74 @@ function SearchableOptions({ sourceId, label, disabled, onPick }) {
}
/**
* One declared param, as the control its type implies (Phase 13).
* The chosen option's note (MODULE_API 1.13.0), found even when the list the
* form holds does not reach it.
*
* A searchable source answers the form a bounded first page, so the value an
* author picked — or a template filled in — may not be in it, and its note with
* it. Then the source is asked for that value as a search term, once per value,
* and the row whose value matches exactly is the one whose note is shown. A
* failure is no note: advice never breaks the field it advises.
*/
function useChosenNote(sourceId, value, entry) {
const [asked, setAsked] = useState({ key: null, note: null })
const text = value === undefined || value === null ? '' : String(value)
const known = noteFor(entry, value)
const needAsk = Boolean(sourceId && entry?.state === 'ok' && entry.searchable && text && !known &&
!entry.options.some((o) => o.value === text))
const key = needAsk ? `${sourceId}\u0000${text}` : null
useEffect(() => {
if (!key || asked.key === key) return undefined
let alive = true
const timer = setTimeout(async () => {
try {
const answer = await api.admin.eventOptions(sourceId, text)
const row = answer?.ok ? (answer.options || []).find((o) => o.value === text) : null
if (alive) setAsked({ key, note: row?.note || null })
} catch {
if (alive) setAsked({ key, note: null })
}
}, 300)
return () => {
alive = false
clearTimeout(timer)
}
}, [key, asked.key, sourceId, text])
if (known) return known
return key && asked.key === key ? asked.note : null
}
/**
* A row of buttons for a choice of two or three (Rust PLAN_REDESIGNS §2.4).
*
* A dropdown of two hides the other choice behind a click; a row shows both and
* which one is on. `aria-pressed` carries the state for a screen reader, the
* opacity for everyone else — the same convention the weekday buttons use.
*/
function Segmented({ choices, value, disabled, onPick }) {
const current = value === undefined || value === null ? '' : String(value)
return (
<div role="group" style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 4 }}>
{choices.map((c) => {
const on = current === String(c.value)
return (
<button key={String(c.value)} type="button" className="pill" disabled={disabled}
aria-pressed={on}
style={{ fontSize: '0.74rem', opacity: on ? 1 : 0.45 }}
onClick={() => onPick(String(c.value))}>
{c.label}
</button>
)
})}
</div>
)
}
/**
* One declared param, as the control its type implies (Phase 13; reworked for
* MODULE_API 1.13.0, Rust PLAN_REDESIGNS §2.1).
*
* **Core does not know what any of this means and that is the design.** The
* label is the param's own name, the help is its own description, the placeholder
@@ -223,32 +300,66 @@ function SearchableOptions({ sourceId, label, disabled, onPick }) {
* the source — `check:modules` fails core's build on a UO identifier, so there is
* nowhere for a game word to be written here even by accident.
*
* Two of the controls are worth their own sentence:
* **The field is the thing it does, not its type.** There is no ` · int` tag and
* no bare asterisk (U-3): a required field says so in words, and only when it is
* empty at save time (`missing`). The controls:
*
* • **A boolean is a three-value select, not a checkbox.** A checkbox cannot say
* *"not set"*, and for an OPTIONAL boolean that is a real third state — the
* action's own default. A checkbox would post `false` for every param an author
* never touched.
* • **A source-backed param keeps its free-text field.** The dropdown writes
* into it; it does not replace it. §F: a source is answered by a module that may
* be talking to a sidecar, and an authoring form a shard outage can make
* unusable is a worse failure than the typo the dropdown exists to prevent.
* • **A boolean is a toggle when it is required and three buttons when it is
* optional** (D334). For an OPTIONAL boolean "not set" is a real third state —
* the action's own default — and a two-state control would post `false` for
* every param an author never touched.
* • **A number shows its range and its unit beside it** when the declaration has
* them: a lease's `min`–`max`, a duration's minutes.
* • **A closed set of two or three is a row of buttons**, whether it is a lease's
* `values` or a source that answered with that few (§2.4).
* • **A source-backed param keeps its free-text field** otherwise. The dropdown
* writes into it; it does not replace it. §F: a source is answered by a module
* that may be talking to a sidecar, and an authoring form a shard outage can
* make unusable is a worse failure than the typo the dropdown exists to
* prevent. A row of buttons replaces the text box only while the source has
* answered and the value is one of its choices.
* • **The chosen option's `note` is shown under the field** (§2.6).
*
* `label`, `range` and `values` are passed by the lease form, which draws one
* lease's fields out of `core.lease`'s generic ones.
*/
function ParamField({ param, value, sourceEntry, disabled, onChange }) {
function ParamField({ param, value, sourceEntry, disabled, onChange, missing, label, range, values }) {
const common = { className: 'input', disabled, style: { fontSize: '0.8rem' } }
const asText = value === undefined || value === null ? '' : String(value)
const placeholder = param.example === undefined || param.example === null ? '' : String(param.example)
let control
let beside = null
if (param.type === 'boolean') {
control = (
<select
{...common}
value={value === true ? 'true' : value === false ? 'false' : ''}
onChange={(e) => onChange(e.target.value)}
>
<option value="">Not set{param.required ? '' : ' — the action decides'}</option>
<option value="true">Yes</option>
<option value="false">No</option>
const b = boolValue(value)
control = param.required ? (
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
<input type="checkbox" role="switch" disabled={disabled} checked={b === true}
onChange={(e) => onChange(e.target.checked ? 'true' : 'false')} />
<span className="sans" style={{ fontSize: '0.8rem' }}>
{b === null ? 'Not set yet' : b ? 'Yes' : 'No'}
</span>
</label>
) : (
<Segmented
disabled={disabled}
value={b === null ? '' : String(b)}
onPick={onChange}
choices={[
{ value: '', label: 'Not set' },
{ value: 'true', label: 'Yes' },
{ value: 'false', label: 'No' },
]}
/>
)
} else if (values && values.length) {
control = values.length <= 3 ? (
<Segmented disabled={disabled} value={asText} onPick={onChange}
choices={values.map((v) => ({ value: v, label: v }))} />
) : (
<select {...common} value={asText} onChange={(e) => onChange(e.target.value)}>
<option value="">Choose…</option>
{values.map((v) => <option key={v} value={v}>{v}</option>)}
</select>
)
} else if (param.type === 'datetime') {
@@ -266,37 +377,67 @@ function ParamField({ param, value, sourceEntry, disabled, onChange }) {
{...common}
type="number"
step={param.type === 'int' ? '1' : 'any'}
min={range?.min ?? undefined}
max={range?.max ?? undefined}
value={asText}
placeholder={param.example === undefined ? '' : String(param.example)}
placeholder={placeholder}
style={{ ...common.style, maxWidth: 180 }}
onChange={(e) => onChange(e.target.value)}
/>
)
const parts = []
if (param.duration === 'minutes') parts.push('minutes')
if (range && range.min !== null && range.min !== undefined && range.max !== null && range.max !== undefined) {
parts.push(`${range.min}–${range.max}`)
} else if (range && range.max !== null && range.max !== undefined) {
parts.push(`at most ${range.max}`)
}
if (parts.length) beside = <span className="sans dim" style={{ fontSize: '0.76rem' }}>{parts.join(' · ')}</span>
} else if (param.type === 'url') {
control = (
<input {...common} type="url" value={asText}
placeholder={param.example === undefined ? '' : String(param.example)}
<input {...common} type="url" value={asText} placeholder={placeholder}
onChange={(e) => onChange(e.target.value)} />
)
} else {
control = (
<input {...common} value={asText}
placeholder={param.example === undefined ? '' : String(param.example)}
<input {...common} value={asText} placeholder={placeholder}
onChange={(e) => onChange(e.target.value)} />
)
}
// A source of two or three answered choices is a row of buttons, and the text
// box goes — unless the value is not one of them, which must stay visible and
// editable rather than look unset.
const segmented = param.source && param.type !== 'boolean' && !values && isSegmentable(sourceEntry)
const offList = segmented && asText !== '' && !sourceEntry.options.some((o) => o.value === asText)
const note = useChosenNote(param.source, value, sourceEntry)
return (
<label style={{ display: 'block', marginBottom: 12 }}>
<span className="field-label">
{param.name}
{param.required && <span style={{ color: '#d98b84' }}> *</span>}
<span className="dim" style={{ fontWeight: 'normal' }}> · {param.type}</span>
</span>
{control}
{param.description && (
<span className="sans dim" style={{ fontSize: '0.74rem' }}>{param.description}</span>
<div style={{ marginBottom: 12 }}>
<label style={{ display: 'block' }}>
<span className="field-label">{label || param.name}</span>
{(!segmented || offList) && (
beside
? <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{control}{beside}</span>
: control
)}
</label>
{segmented && (
<Segmented disabled={disabled} value={asText} onPick={onChange}
choices={sourceEntry.options.map((o) => ({ value: o.value, label: o.label }))} />
)}
{param.source && (
{missing && (
<span className="sans" style={{ display: 'block', fontSize: '0.74rem', color: '#d98b84' }}>
This is required — fill it in before saving.
</span>
)}
{param.description && (
<span className="sans dim" style={{ display: 'block', fontSize: '0.74rem' }}>{param.description}</span>
)}
{note && (
<span className="sans" style={{ display: 'block', fontSize: '0.76rem', color: '#d9c184', marginTop: 4 }}>{note}</span>
)}
{param.source && !segmented && (
sourceEntry?.searchable
? (
<SearchableOptions
@@ -315,7 +456,371 @@ function ParamField({ param, value, sourceEntry, disabled, onChange }) {
/>
)
)}
</label>
</div>
)
}
/**
* A param that holds several values, as a multi-select (MODULE_API 1.14.0; Rust
* PLAN_REDESIGNS §12.3, D344).
*
* The chosen values are chips above the control, each with its remove button,
* and the control is whichever the param's source allows:
*
* • **a source that answered** — a grouped checklist in the source's own order,
* with a filter box over it, because a server's few hundred permissions are a
* list to narrow, not to scroll;
* • **a searchable source** — the typeahead, each pick adding a chip;
* • **no source, or one that failed** — a tag box, a value per Enter. A failure
* is said and the field stays usable, the single-value field's rule (§F).
*
* Ticking past `max` is refused in words, where the click was. The order the
* author picked in is the order stored, and the server keeps it.
*/
function MultiParamField({ param, value, sourceEntry, disabled, onChange, missing }) {
const list = listValue(value)
const [term, setTerm] = useState('')
const [typed, setTyped] = useState('')
const [refused, setRefused] = useState(null)
const max = param.max || 20
const answered = sourceEntry && sourceEntry.state === 'ok'
const byValue = new Map(answered ? sourceEntry.options.map((o) => [o.value, o]) : [])
const add = (v) => {
const next = addToList(list, v, max)
if (next.refused) setRefused(next.refused)
else {
setRefused(null)
onChange(next.list)
}
}
const remove = (v) => {
setRefused(null)
onChange(list.filter((x) => String(x) !== String(v)))
}
const toggle = (v) => (list.some((x) => String(x) === v) ? remove(v) : add(v))
const shown = answered && !sourceEntry.searchable ? filterOptions(sourceEntry.options, term) : []
const groups = [...new Set(shown.map((o) => o.group || ''))]
const chosenNotes = list
.map((v) => ({ v, note: byValue.get(String(v))?.note }))
.filter((x) => x.note)
const tagBox = (
<div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
<input className="input" style={{ fontSize: '0.8rem' }} disabled={disabled} value={typed}
placeholder={param.example === undefined || param.example === null ? '' : String(param.example)}
onChange={(e) => setTyped(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
add(typed)
setTyped('')
}
}} />
<button type="button" className="pill" style={{ fontSize: '0.72rem' }} disabled={disabled || !typed.trim()}
onClick={() => { add(typed); setTyped('') }}>
Add
</button>
</div>
)
let control
if (param.source && sourceEntry?.searchable) {
control = (
<SearchableOptions sourceId={param.source} label={sourceEntry.label || param.source}
disabled={disabled} onPick={add} />
)
} else if (param.source && answered && sourceEntry.options.length) {
control = (
<div style={{ marginTop: 4 }}>
<input className="input" style={{ fontSize: '0.75rem' }} disabled={disabled} value={term}
placeholder={`Filter ${sourceEntry.label || param.source}…`} onChange={(e) => setTerm(e.target.value)} />
<div role="group" aria-label={param.name}
style={{ maxHeight: 240, overflowY: 'auto', marginTop: 4, border: '1px solid rgba(255,255,255,0.08)', padding: '4px 8px' }}>
{shown.length === 0 && (
<div className="dim" style={{ fontSize: '0.72rem' }}>Nothing matches “{term}”.</div>
)}
{groups.map((g) => (
<div key={g || '—'}>
{g && <div className="field-label" style={{ fontSize: '0.7rem', margin: '6px 0 2px' }}>{g}</div>}
{shown.filter((o) => (o.group || '') === g).map((o) => (
<label key={o.value} style={{ display: 'flex', alignItems: 'baseline', gap: 6, fontSize: '0.76rem' }}>
<input type="checkbox" disabled={disabled}
checked={list.some((x) => String(x) === o.value)}
onChange={() => toggle(o.value)} />
<span>{o.label}</span>
{o.note && <span className="dim" style={{ fontSize: '0.7rem' }}>{o.note}</span>}
</label>
))}
</div>
))}
</div>
</div>
)
} else {
control = (
<>
{param.source && (
<ParamOptions entry={sourceEntry} label={sourceEntry?.label || param.source} disabled={disabled} onPick={add} />
)}
{tagBox}
</>
)
}
return (
<div style={{ marginBottom: 12 }}>
<span className="field-label">
{param.name} <span className="dim" style={{ fontWeight: 'normal' }}>· {list.length} of at most {max}</span>
</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 4 }}>
{list.length === 0 && <span className="sans dim" style={{ fontSize: '0.76rem' }}>None chosen yet.</span>}
{list.map((v) => (
<span key={String(v)} className="pill" style={{ fontSize: '0.74rem', display: 'inline-flex', gap: 6, alignItems: 'center' }}>
{byValue.get(String(v))?.label || String(v)}
<button type="button" aria-label={`Remove ${v}`} disabled={disabled}
style={{ background: 'none', border: 'none', color: 'inherit', cursor: 'pointer', padding: 0 }}
onClick={() => remove(v)}>
×
</button>
</span>
))}
</div>
{refused && (
<span className="sans" style={{ display: 'block', fontSize: '0.74rem', color: '#d98b84', marginTop: 4 }}>{refused}</span>
)}
{control}
{missing && (
<span className="sans" style={{ display: 'block', fontSize: '0.74rem', color: '#d98b84' }}>
This is required — choose at least one before saving.
</span>
)}
{param.description && (
<span className="sans dim" style={{ display: 'block', fontSize: '0.74rem' }}>{param.description}</span>
)}
{chosenNotes.map(({ v, note }) => (
<span key={String(v)} className="sans" style={{ display: 'block', fontSize: '0.76rem', color: '#d9c184', marginTop: 4 }}>
{byValue.get(String(v))?.label || String(v)}: {note}
</span>
))}
</div>
)
}
/**
* `core.lease`, drawn as the chosen lease (Rust PLAN_REDESIGNS §2.1, U-4, F11).
*
* `core.lease` declares four generic fields — a lease id, a value as text, a
* target as text, a number of minutes — because one action serves every lease
* there is. Drawn as declared, a Rust admin was shown a skill-gain rate as the
* example and a free-text box for a target the lease has a list of. So the
* lease is picked by its label, and the other three become that lease's own:
*
* • the value as the lease's type — a toggle, a number with the lease's range,
* or its closed set of values — with the lease's own example;
* • the target as a picker over the lease's own `target.source` (F11: the editor
* read only `param.source`, and `core.lease`'s target param has none, on
* purpose — see its declaration);
* • the minutes with the lease's longest hold beside them.
*
* What is written is still `core.lease`'s params, as text where the action says
* text: the action coerces the value to the lease's type, and that stays the one
* place that knows both halves.
*/
function LeaseFields({ action, step, leases, sources, disabled, missing, onParam }) {
const declared = new Map((action.params || []).map((p) => [p.name, p]))
const leaseId = paramValue(step, 'lease')
const lease = leases.find((l) => l.id === leaseId) || null
const target = paramValue(step, 'target')
const owners = [...new Set(leases.map((l) => l.owner || 'other'))]
return (
<>
<div style={{ marginBottom: 12 }}>
<label style={{ display: 'block' }}>
<span className="field-label">What to borrow</span>
<select className="input" style={{ fontSize: '0.8rem' }} disabled={disabled} value={leaseId || ''}
onChange={(e) => onParam('lease', e.target.value)}>
<option value="">Pick a value to borrow…</option>
{owners.map((owner) => (
<optgroup key={owner} label={owner}>
{leases.filter((l) => (l.owner || 'other') === owner).map((l) => (
<option key={l.id} value={l.id}>{l.label}</option>
))}
</optgroup>
))}
{leaseId && !lease && <option value={leaseId}>{leaseId} (not installed)</option>}
</select>
</label>
{missing.includes('lease') && (
<span className="sans" style={{ display: 'block', fontSize: '0.74rem', color: '#d98b84' }}>
This is required — fill it in before saving.
</span>
)}
{lease?.description && (
<span className="sans dim" style={{ display: 'block', fontSize: '0.74rem' }}>{lease.description}</span>
)}
{leaseId && !lease && (
<span className="sans" style={{ display: 'block', fontSize: '0.74rem', color: '#d9c184' }}>
No installed module declares <code>{leaseId}</code>.
</span>
)}
</div>
{lease && (
<ParamField
param={{
name: 'value',
type: lease.type === 'bool' ? 'boolean' : lease.type,
required: true,
example: lease.example ?? (lease.type === 'int' || lease.type === 'float' ? lease.min : ''),
}}
label="Hold it at"
range={lease.type === 'int' || lease.type === 'float' ? { min: lease.min, max: lease.max } : null}
values={lease.values}
value={paramValue(step, 'value')}
disabled={disabled}
missing={missing.includes('value')}
onChange={(raw) => onParam('value', raw)}
/>
)}
{lease?.target && (
<ParamField
param={{
name: 'target',
type: 'string',
required: true,
example: lease.target.example ?? '',
source: lease.target.source,
description: lease.target.description,
}}
label={lease.target.label}
value={target}
sourceEntry={lease.target.source ? sources[lease.target.source] : null}
disabled={disabled}
missing={missing.includes('target')}
onChange={(raw) => onParam('target', raw)}
/>
)}
{lease && !lease.target && target !== undefined && target !== '' && (
<p className="sans" style={{ fontSize: '0.76rem', color: '#d9c184', margin: '0 0 12px' }}>
{lease.label} is a single value and takes no target, so the step will be refused with
<code> {String(target)}</code> in it.{' '}
<button type="button" className="pill" style={{ fontSize: '0.7rem' }} disabled={disabled}
onClick={() => onParam('target', '')}>
Clear it
</button>
</p>
)}
{declared.get('minutes') && (
<ParamField
param={declared.get('minutes')}
label="For how long"
range={lease ? { min: 1, max: Math.floor(lease.maxDurationMs / 60_000) } : null}
value={paramValue(step, 'minutes')}
disabled={disabled}
missing={missing.includes('minutes')}
onChange={(raw) => onParam('minutes', raw)}
/>
)}
</>
)
}
/**
* "Start from a template" on a new event (MODULE_API 1.13.0; Rust PLAN_REDESIGNS
* §2.5, D192).
*
* A module's named starting point: the author fills in a few inputs and gets an
* ordinary draft in the editor below — the title, the phases, the steps — which
* they read, change and save like any other. **Nothing is saved here**, and
* nothing about the template follows the definition: it is a shortcut past
* typing, and the editor is still where the event is made.
*
* The inputs are params and are drawn by `ParamField`, so an input with a source
* gets the same dropdown, buttons and search a step's field does.
*/
function TemplatePicker({ templates, sources, loadSource, onDraft }) {
const [chosenId, setChosenId] = useState('')
const [inputs, setInputs] = useState({})
const [errors, setErrors] = useState([])
const [busy, setBusy] = useState(false)
const chosen = templates.find((t) => t.id === chosenId) || null
useEffect(() => {
for (const p of chosen?.inputs || []) if (p.source) loadSource(p.source)
}, [chosen, loadSource])
const choose = (id) => {
setChosenId(id)
setErrors([])
const t = templates.find((x) => x.id === id)
// Prefilled from the examples, like a fresh step — but only the required
// ones, because an example of a kit is not a kit this deployment has.
setInputs({})
if (t) setInputs(Object.fromEntries(t.inputs.filter((p) => p.required && !p.source).map((p) => [p.name, p.example])))
}
const fill = async () => {
setBusy(true)
setErrors([])
try {
const { draft } = await api.admin.buildEventTemplate(chosen.id, inputs)
onDraft(draft, chosen)
} catch (err) {
setErrors(err.body?.errors || [err.message])
} finally {
setBusy(false)
}
}
return (
<div className="panel-flat" style={{ padding: 14, marginBottom: 14, borderLeft: '3px solid var(--accent, #6d7f9c)' }}>
<h3 className="sans" style={{ margin: '0 0 6px', fontSize: '0.92rem' }}>Start from a template</h3>
<p className="sans dim" style={{ margin: '0 0 10px', fontSize: '0.78rem' }}>
A starting point an installed module offers. It fills in the plan below; nothing is saved
until you create the draft, and you can change every part of it first.
</p>
<select className="input" style={{ fontSize: '0.8rem', maxWidth: 360 }} value={chosenId}
onChange={(e) => choose(e.target.value)}>
<option value="">Start from nothing</option>
{templates.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
</select>
{chosen && (
<div style={{ marginTop: 12 }}>
{chosen.description && (
<p className="sans dim" style={{ margin: '0 0 10px', fontSize: '0.8rem' }}>{chosen.description}</p>
)}
{chosen.inputs.map((p) => (
<ParamField
key={p.name}
param={p}
value={inputs[p.name]}
sourceEntry={p.source ? sources[p.source] : null}
disabled={busy}
onChange={(raw) => setInputs((cur) => {
const next = { ...cur }
if (raw === '' || raw === undefined || raw === null) delete next[p.name]
else next[p.name] = coerceLiteral(p.type, raw)
return next
})}
/>
))}
{errors.length > 0 && (
<ul className="sans" style={{ margin: '0 0 10px', paddingLeft: 18, fontSize: '0.8rem', color: '#d98b84' }}>
{errors.map((e) => <li key={e}>{e}</li>)}
</ul>
)}
<button type="button" className="pill" style={{ fontSize: '0.74rem' }} disabled={busy} onClick={fill}>
Fill in the plan
</button>
</div>
)}
</div>
)
}
@@ -404,7 +909,7 @@ function WhereBuilder({ advance, trigger, operators, disabled, onChange }) {
{!valueless && (
<input className="input" style={{ flex: '1 1 140px', fontSize: '0.76rem' }} value={row.value ?? ''}
disabled={disabled || !row.cmp}
placeholder={row.cmp === 'in' || row.cmp === 'nin' ? 'Yew, Britain, Vesper' : ''}
placeholder={row.cmp === 'in' || row.cmp === 'nin' ? 'north, south, east' : ''}
onChange={(e) => setRow(i, { value: e.target.value })} />
)}
<button type="button" className="pill" style={{ fontSize: '0.72rem' }} disabled={disabled}
@@ -525,11 +1030,17 @@ function CapMeter({ report, budgets, stale }) {
* are ceilinged to `staff`. It is not a dry run and the dialog says so, because
* the two words are near enough to swap in a hurry.
*/
function StartDialog({ onStart, onCancel, busy }) {
function StartDialog({ onStart, onCancel, busy, draftAhead, publishedVersion, mayPublish }) {
const [rehearsal, setRehearsal] = useState(false)
const [scope, setScope] = useState('')
const [paramsText, setParamsText] = useState('{}')
const [problem, setProblem] = useState(null)
// Rust PLAN_REDESIGNS §2.3 (U-5). A run is pinned to the PUBLISHED version, so
// an author who saved an edit and pressed Start ran the old plan without being
// told. When the working copy is ahead, the dialog asks which one — and does
// not pick for them: publishing is a decision with consequences of its own
// (scheduled occurrences move to the new version).
const [which, setWhich] = useState(null)
const go = () => {
let params = null
@@ -546,13 +1057,43 @@ function StartDialog({ onStart, onCancel, busy }) {
return
}
}
onStart({ rehearsal, scope: scope || undefined, ...(params ? { params } : {}) })
if (draftAhead && !which) {
setProblem('Choose which plan to start: your edits, published first, or the published version.')
return
}
onStart(
{ rehearsal, scope: scope || undefined, ...(params ? { params } : {}) },
{ publishFirst: draftAhead && which === 'publish' },
)
}
return (
<div className="panel-flat" style={{ padding: 14, marginBottom: 14, borderLeft: '3px solid var(--accent, #6d7f9c)' }}>
<h3 className="sans" style={{ margin: '0 0 10px', fontSize: '0.92rem' }}>Start a run now</h3>
{draftAhead && (
<div style={{ marginBottom: 12, borderLeft: '3px solid #d9c184', paddingLeft: 10 }}>
<p className="sans" style={{ margin: '0 0 6px', fontSize: '0.84rem' }}>
<strong>This definition has edits that are not published.</strong>{' '}
<span className="dim">A run uses a published version, never the working copy.</span>
</p>
{mayPublish && (
<label style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
<input type="radio" name="start-which" checked={which === 'publish'} onChange={() => setWhich('publish')} />
<span className="sans" style={{ fontSize: '0.84rem' }}>
Publish and start <span className="dim">— your edits become v{(publishedVersion || 0) + 1}, and scheduled occurrences move to it</span>
</span>
</label>
)}
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input type="radio" name="start-which" checked={which === 'published'} onChange={() => setWhich('published')} />
<span className="sans" style={{ fontSize: '0.84rem' }}>
Start version {publishedVersion} <span className="dim">(the published one, without your edits)</span>
</span>
</label>
</div>
)}
<label style={{ display: 'flex', gap: 8, alignItems: 'flex-start', marginBottom: 10 }}>
<input type="checkbox" checked={rehearsal} onChange={(e) => setRehearsal(e.target.checked)} />
<span className="sans" style={{ fontSize: '0.84rem' }}>
@@ -684,6 +1225,14 @@ export default function EventEditor() {
// refuses is the failure this avoids.
const triggers = useMemo(() => catalog?.triggers || [], [catalog])
const triggerById = useMemo(() => new Map(triggers.map((t) => [t.id, t])), [triggers])
// Rust PLAN_REDESIGNS §2.1: `core.lease` is drawn as the chosen lease.
const leases = useMemo(() => catalog?.leases || [], [catalog])
const leaseById = useMemo(() => new Map(leases.map((l) => [l.id, l])), [leases])
// §2.5: a new event may start from a module's template.
const templates = useMemo(() => catalog?.templates || [], [catalog])
// §2.1: a required field says it is empty only once a save has been tried —
// a form that opens covered in red reads as broken before anyone has typed.
const [checkMissing, setCheckMissing] = useState(false)
// Phase 7. source id -> { state: 'loading' | 'ok' | 'failed', options, reason }.
//
@@ -747,10 +1296,16 @@ export default function EventEditor() {
for (const p of actionById.get(step.actionId)?.params || []) {
if (p.source) wanted.add(p.source)
}
// A lease step's target list is the chosen LEASE's (F11), which only
// becomes knowable once a lease is picked.
if (step.actionId === 'core.lease') {
const source = leaseById.get(paramValue(step, 'lease'))?.target?.source
if (source) wanted.add(source)
}
}
}
for (const id of wanted) loadSource(id)
}, [form, actionById, loadSource])
}, [form, actionById, leaseById, loadSource])
/**
* The live cap meter (§I, Phase 13).
@@ -806,14 +1361,6 @@ export default function EventEditor() {
phases: f.phases.map((p, i) => (i === pi ? { ...p, ...patch } : p)),
}))
const setStep = (pi, si, patch) =>
setForm((f) => ({
...f,
phases: f.phases.map((p, i) =>
i === pi ? { ...p, steps: p.steps.map((s, j) => (j === si ? { ...s, ...patch } : s)) } : p,
),
}))
const movePhase = (pi, delta) =>
setForm((f) => {
const next = [...f.phases]
@@ -848,13 +1395,65 @@ export default function EventEditor() {
const changeAction = (pi, si, actionId) => {
const action = actionById.get(actionId)
const fresh = blankStep(action)
setStep(pi, si, { actionId, label: fresh.label, paramsText: fresh.paramsText, onFailure: '' })
setStep(pi, si, { actionId, label: fresh.label, paramsText: fresh.paramsText, onFailure: '' }, { timed: true })
}
/**
* Write one step and, when the change could make it a timed step, keep its
* phase open long enough for it (Rust PLAN_REDESIGNS §2.2, U-6).
*
* Teardown gives a held thing back when the run ends, so a lease "for 10
* minutes" in a one-phase event with no advance rule lasted a second. Only a
* phase with NO rule is given one — `after: <the longest hold>`, on the screen,
* for the author to change; a rule the author chose is left alone and the
* sentence under the phase says what it costs. Only changes that can create or
* lengthen a hold ask (`timed`), so an author who removed the rule on purpose
* and then edits a message is not overruled.
*/
const setStep = (pi, si, patch, { timed = false } = {}) =>
setForm((f) => {
const phases = f.phases.map((p, i) =>
i === pi ? { ...p, steps: p.steps.map((s, j) => (j === si ? { ...s, ...patch } : s)) } : p,
)
if (!timed) return { ...f, phases }
const advance = guardedAdvance(phases, pi, actionById)
return { ...f, phases: advance ? phases.map((p, i) => (i === pi ? { ...p, advance } : p)) : phases }
})
const addStep = (pi) =>
setForm((f) => {
const phases = f.phases.map((p, i) => (i === pi ? { ...p, steps: [...p.steps, blankStep(actions[0])] } : p))
const advance = guardedAdvance(phases, pi, actionById)
return { ...f, phases: advance ? phases.map((p, i) => (i === pi ? { ...p, advance } : p)) : phases }
})
/** One param of one step, from a form control. */
const setStepParam = (pi, si, step, param, raw) =>
setStep(pi, si, { paramsText: setParam(step, param.name, raw, param.type) }, { timed: Boolean(param.duration) })
/** Every required field the plan leaves empty, as the sentences the save shows. */
const missingSentences = () => {
const out = []
form.phases.forEach((phase, pi) => phase.steps.forEach((step, si) => {
for (const name of missingParams(step, actionById.get(step.actionId), leaseById)) {
out.push(`Phase ${pi + 1} "${phase.label || phase.key}", step ${si + 1}: ${name} is required`)
}
}))
return out
}
const save = async () => {
setBusy(true)
setProblems([])
setNotice(null)
// §2.1: a required field left empty is named under the field AND in the
// list, here, before the round trip the server would refuse it on anyway.
setCheckMissing(true)
const missing = missingSentences()
if (missing.length) {
setProblems(missing)
return
}
setBusy(true)
// A report describes a spec, and saving changes it. A green report left
// standing beside an edited plan is worse than no report at all.
setReport(null)
@@ -946,10 +1545,17 @@ export default function EventEditor() {
* not be started correctly at all: every manual run rendered the same key and
* the second was refused as an overlap with the first.
*/
const start = async (body) => {
const start = async (body, { publishFirst = false } = {}) => {
setBusy(true)
setProblems([])
try {
// §2.3: "Publish and start" is the two calls an admin would otherwise
// make by hand, in order, and a publish the server refuses stops here
// rather than starting the old version behind the author's back.
if (publishFirst) {
const published = await api.admin.publishEvent(id)
setEvent(published.event)
}
const result = await api.admin.startEventRun(id, body)
navigate(`/admin/events/runs/${result.run.id}`)
} catch (err) {
@@ -1113,7 +1719,8 @@ export default function EventEditor() {
)}
{starting && (
<StartDialog busy={busy} onCancel={() => setStarting(false)} onStart={start} />
<StartDialog busy={busy} onCancel={() => setStarting(false)} onStart={start}
draftAhead={Boolean(event?.draftAhead)} publishedVersion={event?.currentVersion} mayPublish={isAdmin} />
)}
{notice && <p className="sans" style={{ fontSize: '0.84rem', color: '#8fc79a' }}>{notice}</p>}
@@ -1127,6 +1734,19 @@ export default function EventEditor() {
</div>
)}
{isNew && mayAuthor && templates.length > 0 && (
<TemplatePicker
templates={templates}
sources={sources}
loadSource={loadSource}
onDraft={(draft, template) => {
setForm(formFromDefinition({ title: draft.title, summary: draft.summary, spec: draft.spec }))
setProblems([])
setNotice(`Filled in from "${template.label}". Nothing is saved until you create the draft.`)
}}
/>
)}
{/* ── Basics ── */}
<div className="panel-flat" style={{ padding: 14, marginBottom: 14 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 12 }}>
@@ -1399,6 +2019,14 @@ export default function EventEditor() {
? 'This is in ADDITION to its steps: the phase waits until every step has finished AND this is met. Nothing times out — if the condition never happens, the run is marked stalled and a person advances it from the run console.'
: 'The phase advances the moment every one of its steps is finished.'}
</p>
{/* §2.2 (U-6). A held value is given back when the RUN ends, so a
plan that can end sooner than its longest hold is said out loud
here, where the rule that decides it is. */}
{shortfallSentence(form.phases, pi, actionById) && (
<p className="sans" style={{ fontSize: '0.78rem', color: '#d9c184', margin: '6px 0 0' }}>
{shortfallSentence(form.phases, pi, actionById)}
</p>
)}
</div>
<div style={{ marginTop: 12 }}>
@@ -1479,16 +2107,43 @@ export default function EventEditor() {
{mode.mode === PARAM_FORM ? (
<div style={{ marginTop: 8 }}>
{(action?.params || []).map((p) => (
{action?.id === 'core.lease' ? (
<LeaseFields
action={action}
step={step}
leases={leases}
sources={sources}
disabled={archived}
missing={checkMissing ? missingParams(step, action, leaseById) : []}
onParam={(name, raw) => {
const declared = action.params.find((p) => p.name === name)
// A new lease changes which hold this is, so it is
// checked like a new duration.
setStep(pi, si, { paramsText: setParam(step, name, raw, declared.type) },
{ timed: name === 'lease' || Boolean(declared.duration) })
}}
/>
) : (action?.params || []).map((p) => (p.multiple ? (
<MultiParamField
key={p.name}
param={p}
value={paramValue(step, p.name)}
sourceEntry={p.source ? sources[p.source] : null}
disabled={archived}
missing={checkMissing && missingParams(step, action, leaseById).includes(p.name)}
onChange={(list) => setStep(pi, si, { paramsText: setParamList(step, p.name, list, p.type) })}
/>
) : (
<ParamField
key={p.name}
param={p}
value={paramValue(step, p.name)}
sourceEntry={p.source ? sources[p.source] : null}
disabled={archived}
onChange={(raw) => setStep(pi, si, { paramsText: setParam(step, p.name, raw, p.type) })}
missing={checkMissing && missingParams(step, action, leaseById).includes(p.name)}
onChange={(raw) => setStepParam(pi, si, step, p, raw)}
/>
))}
)))}
{action && (action.params || []).length === 0 && (
<p className="sans dim" style={{ fontSize: '0.78rem', margin: 0 }}>
This action takes no params.
@@ -1509,7 +2164,7 @@ export default function EventEditor() {
{action && (action.params || []).length > 0 && (
<span className="sans dim" style={{ fontSize: '0.74rem' }}>
<code>{action.id}</code> declares{' '}
{(action.params || []).map((p) => `${p.name} (${p.type}${p.required ? ', required' : ''})`).join(', ')}.
{(action.params || []).map((p) => `${p.name} (${p.multiple ? `a list of ${p.type}, at most ${p.max}` : p.type}${p.required ? ', required' : ''})`).join(', ')}.
</span>
)}
</>
@@ -1520,7 +2175,7 @@ export default function EventEditor() {
})}
<button type="button" className="pill" style={{ fontSize: '0.72rem', marginTop: 12 }} disabled={archived}
onClick={() => setPhase(pi, { steps: [...phase.steps, blankStep(actions[0])] })}>
onClick={() => addStep(pi)}>
Add step
</button>
</div>

View File

@@ -9,6 +9,7 @@ import {
runControlsFor,
stepControlsFor,
describeLogLine,
describeParams,
} from '../../../lib/eventAuthoring.js'
// Admin → Events → the run console (EVENTS.md §I, Phase 3).
@@ -59,7 +60,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 +72,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 +84,7 @@ const RESOURCE_WORD = {
reverted: 'given back',
orphaned: 'gone',
drifted: 'someone else moved it',
expired: 'ended by the game on time',
}
const STEP_COLOR = {
@@ -651,7 +656,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,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

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

@@ -323,6 +323,37 @@ function validateAdvance(raw, path, errors) {
return { on: triggerId, where: checked.conditions, count, dormant: false }
}
/**
* 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 +380,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
@@ -603,6 +642,9 @@ 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,

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

@@ -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

@@ -78,6 +78,16 @@ 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),
})
const shapeRun = (r) => ({
id: r.id,
definitionId: r.definition_id,
@@ -203,6 +213,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,
@@ -363,7 +376,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 +421,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 +436,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 +598,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.'
// #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" } } } } */

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

@@ -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.",
"parameters": [
{
"name": "runId",
@@ -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

@@ -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

@@ -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', () => {