feat(events): the minimal admin surface (Phase 3)
All checks were successful
PR Checks / bot-tests (pull_request) Successful in 30s
PR Checks / server-tests (pull_request) Successful in 5m26s
PR Checks / client-build (pull_request) Successful in 8m30s

Three screens, an Events nav group and the six live run controls Phase 1 left
absent on purpose because nothing was in flight. An admin can now author,
publish, start and watch an event that announces things and cues a human; a
moderator can stop one that is going wrong.

Six controls, not eight. `advance` is absent because a phase today advances when
its steps go terminal — the per-step skip already does that — and Phase 5 is what
gives a phase an advance condition. Cancel takes `{ reason }`, not `{ cleanup }`,
until Phase 8's ledger exists. Every control is a compare-and-set on the status it
may act from, so a console rendered thirty seconds ago cannot act on a run that
has moved.

Fixes a defect in the Phase 2 runner: `advanceRun` drained up to
EVENT_STEPS_PER_TICK steps while only checking the run's status at the top of the
tick, so a pause pressed mid-batch did nothing for up to 24 more steps.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T6t8mrAWhZU5vnyYgZTMtL
This commit is contained in:
2026-09-02 08:39:35 -05:00
parent 2ba397eff7
commit 7b570c8ea1
20 changed files with 3775 additions and 8 deletions

View File

@@ -8,10 +8,14 @@
// a definition arriving from a future import or a restore gets the same answer
// this screen does.
//
// **What is deliberately absent**: pause, resume, advance, cancel, step
// skip/retry/confirm, cleanup and the action switchboard. Each of them acts on a
// run in flight, and nothing is in flight until Phase 2 builds the runner. A
// control that returns 200 and does nothing is worse than one that is not there.
// **Phase 3 added the live run controls** at the bottom of this file: pause,
// resume, cancel, and a step's confirm, skip and retry. What is still absent is
// `advance`, `cleanup` and the action switchboard — `advance` has no honest
// meaning until Phase 5 gives a phase an advance condition, `cleanup` has no
// ledger to work over until Phase 8, and the switchboard is Phase 6's. Each of
// them is absent rather than stubbed, for the reason the whole set was in Phase
// 1: a control that returns 200 and does nothing is worse than one that is not
// there.
const registries = require('../../../modules/registries')
const spec = require('../../../events/spec')
@@ -21,6 +25,7 @@ const versionsDb = require('../../../model/events/eventVersions.db')
const seriesDb = require('../../../model/events/eventSeries.db')
const runsDb = require('../../../model/events/eventRuns.db')
const runs = require('../../../model/events/eventRuns.model')
const controls = require('../../../model/events/eventRunControls.model')
const logDb = require('../../../model/events/eventRunLog.db')
const activity = require('../../../model/activity/activity.model')
@@ -80,6 +85,10 @@ const shapeRun = (r) => ({
endedAt: r.ended_at,
lastError: r.last_error,
createdAt: r.created_at,
// How many steps are parked on a human. Derived, not a column, and surfaced on
// the LIST as well as the console because a cue nobody notices is a run that
// never advances while looking perfectly healthy from the outside.
waitingSteps: Number(r.waiting_steps || 0),
})
const shapeStep = (s) => ({
@@ -91,6 +100,12 @@ const shapeStep = (s) => ({
params: s.params,
actionVersion: s.action_version,
status: s.status,
// `running` with no lease is a parked step (§E) — waiting on a human, with
// nothing holding it. The console has to tell that apart from a step some
// process is mid-dispatch on, and it must not do so by being shown the lease:
// one derived boolean rather than `claimed_by` and `claim_expires_at`, which
// are the runner's business and would invite a UI that reasoned about leases.
parked: s.status === 'running' && !s.claim_expires_at,
dueAt: s.due_at,
attempts: s.attempts,
onFailure: s.on_failure,
@@ -313,3 +328,89 @@ exports.startRun = async (req, res) => {
created: result.created,
})
}
// ── Phase 3: the live run controls ─────────────────────────────────────────
//
// Six handlers, and each is the same four lines: read the ids out of the URL,
// hand off to `eventRunControls`, log the manual transition to `activity_log`,
// answer with the row. Every guard is in the model, where a control invoked from
// anywhere else gets the same answer — which is the same division this file has
// had since Phase 1.
//
// **The audit is written in two places on purpose, and they are not redundant.**
// `event_run_log` is the run's own diagnostic record: queryable by phase and by
// step, and it is what the console renders. `activity_log` is the deployment's
// record of what staff did, and it is where "who cancelled the invasion" is
// looked up months later by somebody who is not looking at that run. §J names
// both.
/** POST /api/v1/admin/events/runs/:runId/pause */
exports.pauseRun = async (req, res) => {
const runId = asId(req.params.runId)
if (!runId) return res.status(400).json({ error: 'bad run id' })
const result = await controls.pause(runId, { reason: req.body?.reason }, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({ req, action: 'event.run.paused', detail: { runId, reason: req.body?.reason || null } })
return res.json({ run: shapeRun(result.run) })
}
/** POST /api/v1/admin/events/runs/:runId/resume */
exports.resumeRun = async (req, res) => {
const runId = asId(req.params.runId)
if (!runId) return res.status(400).json({ error: 'bad run id' })
const result = await controls.resume(runId, {}, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({ req, action: 'event.run.resumed', detail: { runId } })
return res.json({ run: shapeRun(result.run) })
}
/** POST /api/v1/admin/events/runs/:runId/cancel */
exports.cancelRun = async (req, res) => {
const runId = asId(req.params.runId)
if (!runId) return res.status(400).json({ error: 'bad run id' })
const result = await controls.cancel(runId, { reason: req.body?.reason }, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({
req,
action: 'event.run.cancelled',
detail: { runId, reason: req.body?.reason || null, cancelledSteps: result.cancelledSteps },
})
return res.json({ run: shapeRun(result.run), cancelledSteps: result.cancelledSteps })
}
/** POST /api/v1/admin/events/runs/:runId/steps/:stepId/confirm */
exports.confirmStep = async (req, res) => {
const runId = asId(req.params.runId)
const stepId = asId(req.params.stepId)
if (!runId || !stepId) return res.status(400).json({ error: 'bad run or step id' })
const result = await controls.confirmStep(runId, stepId, { note: req.body?.note }, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({ req, action: 'event.step.confirmed', detail: { runId, stepId, action: result.step.action_id } })
return res.json({ step: shapeStep(result.step) })
}
/** POST /api/v1/admin/events/runs/:runId/steps/:stepId/skip */
exports.skipStep = async (req, res) => {
const runId = asId(req.params.runId)
const stepId = asId(req.params.stepId)
if (!runId || !stepId) return res.status(400).json({ error: 'bad run or step id' })
const result = await controls.skipStep(runId, stepId, { reason: req.body?.reason }, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({
req,
action: 'event.step.skipped',
detail: { runId, stepId, action: result.step.action_id, reason: req.body?.reason || null },
})
return res.json({ step: shapeStep(result.step) })
}
/** POST /api/v1/admin/events/runs/:runId/steps/:stepId/retry */
exports.retryStep = async (req, res) => {
const runId = asId(req.params.runId)
const stepId = asId(req.params.stepId)
if (!runId || !stepId) return res.status(400).json({ error: 'bad run or step id' })
const result = await controls.retryStep(runId, stepId, {}, req.user.id)
if (!result.ok) return res.status(result.status || 409).json({ errors: result.errors })
await activity.log({ req, action: 'event.step.retried', detail: { runId, stepId, action: result.step.action_id } })
return res.json({ step: shapeStep(result.step), run: shapeRun(result.run), resumed: result.resumed })
}

View File

@@ -12,9 +12,11 @@
// are here anyway, because a button that is admin-only later and open now is a
// gate nobody notices was missing.
//
// Reads are staff-wide. `verify` (admin, editor) is Phase 6's, and the live run
// controls (admin, moderator) are Phase 3's — neither is stubbed here, because
// nothing is in flight until Phase 2 builds the runner.
// Reads are staff-wide. The live run controls landed in Phase 3 and are `admin`
// + `moderator`, deliberately wider than start (§N2). `verify` (admin, editor),
// `advance`, `cleanup` and the action switchboard are still absent rather than
// stubbed — there is no advance condition until Phase 5, no resource ledger
// until Phase 8 and no caps to price against until Phase 6.
//
// **Literal paths are declared before `/:id`**, so `/catalog`, `/series` and
// `/runs` are never read as an event id.
@@ -27,6 +29,10 @@ const { requireRole } = require('../../../utils/auth')
const eventsRouter = express.Router()
const adminOnly = requireRole('admin')
const adminOrEditor = requireRole('admin', 'editor')
// Live control of a run in flight, and the one gate wider than `admin` in this
// feature (§K). Named rather than inlined so the six routes below cannot drift
// apart from one another.
const liveControl = requireRole('admin', 'moderator')
// ── The catalog and the vocabularies, served from the registries ───────────
@@ -93,6 +99,105 @@ eventsRouter.get(
controller.getRunLog,
)
// ── The live run controls (Phase 3) ───────────────────────────────────────
//
// `admin` + `moderator`, and it is the widest gate in this feature deliberately
// (§K, §N2). Starting a run commits the deployment to everything the definition
// contains, unattended, up to every cap it declares — that wants the narrowest
// gate there is. Stopping one is incident response, and the incident is "the
// event is doing something wrong at 2am" — that wants the widest. A split that
// read consistent, with one role owning both buttons, would behave badly in
// exactly the case the moderator role exists for.
//
// `advance` and `cleanup` from the § API surface table are not here: the first
// has no honest meaning until Phase 5 gives a phase an advance condition, the
// second has no resource ledger to work over until Phase 8.
eventsRouter.post(
'/runs/:runId/pause',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Pause a run in flight'
// #swagger.description = 'A paused run is excluded from the runner\'s sweep and nothing advances it until resume. Legal from `starting` and `running` only — a `scheduled` occurrence that should not happen is cancelled, not paused, because resuming one after its grace window had passed would produce a `missed` from a button labelled resume. Takes effect at once even mid-tick: the runner re-reads the run\'s status between steps.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { reason: { type: "string", description: "Recorded in the run log with the actor" } } } } } } */
/* #swagger.responses[200] = { description: 'The paused run', content: { "application/json": { schema: { type: "object", properties: { run: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[409] = { description: 'The run is not in flight', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.pauseRun,
)
eventsRouter.post(
'/runs/:runId/resume',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Resume a paused run'
// #swagger.description = 'Where the run goes back to is derived rather than remembered: a paused run with a `current_phase` was running, one without never got past `starting`. `last_error` is cleared — the operator has just dealt with it — and `health` is not, because "this run has already had trouble" stays true whoever pressed resume.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The resumed run', content: { "application/json": { schema: { type: "object", properties: { run: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[409] = { description: 'The run is not paused', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.resumeRun,
)
eventsRouter.post(
'/runs/:runId/cancel',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Cancel a run'
// #swagger.description = 'Legal from every non-terminal status, `scheduled` included. Pending steps and any parked cue are cancelled with it; a step with a live lease is left alone, because nothing can recall a command already sent and a second writer on that row would race the process dispatching it. `cleanup` is not a parameter yet — the resource ledger it would work over arrives in Phase 8, and a flag that changes nothing is worse than one that is not there.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { reason: { type: "string", description: "Why. Recorded on the run and in its log, with the actor." } } } } } } */
/* #swagger.responses[200] = { description: 'The cancelled run and how many steps were closed out with it', content: { "application/json": { schema: { type: "object", properties: { run: { type: "object", additionalProperties: true }, cancelledSteps: { type: "integer" } } } } } } */
/* #swagger.responses[409] = { description: 'The run has already reached a terminal status', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.cancelRun,
)
eventsRouter.post(
'/runs/:runId/steps/:stepId/confirm',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Confirm a parked step — the GM cue'
// #swagger.description = 'The other half of `core.cue`. The action posts an instruction and parks the step `running` with a NULL lease — genuinely in flight, nothing holding it, so no sweep takes it back and a cue posted on Friday is still waiting on Monday. This ends it, as `done` rather than `skipped`: a person saying they did the thing is the step having succeeded. The optional note is what they did, and it is kept on the step and in the log.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { note: { type: "string", description: "What was actually done in-client" } } } } } } */
/* #swagger.responses[200] = { description: 'The confirmed step', content: { "application/json": { schema: { type: "object", properties: { step: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[404] = { description: 'No such run, or no such step on it', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'The step is not waiting on anyone', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.confirmStep,
)
eventsRouter.post(
'/runs/:runId/steps/:stepId/skip',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Skip a step nobody is going to run'
// #swagger.description = 'A step that has not started, or a parked cue. This is what the `skipped` status was reserved for, and why all three `on_failure` dispositions write `failed` instead — a status meaning both "a human decided against this" and "this was attempted three times and never worked" would make the console summary unreadable. A step with a live lease cannot be skipped; a failed one does not need to be, because resuming the run already carries the phase past it.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { reason: { type: "string" } } } } } } */
/* #swagger.responses[200] = { description: 'The skipped step', content: { "application/json": { schema: { type: "object", properties: { step: { type: "object", additionalProperties: true } } } } } } */
/* #swagger.responses[404] = { description: 'No such run, or no such step on it', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'The step or its run is in a status that cannot be skipped', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.skipStep,
)
eventsRouter.post(
'/runs/:runId/steps/:stepId/retry',
// #swagger.tags = ['Admin · Events']
// #swagger.summary = 'Re-queue the failed step a paused run is stopped at, and resume it'
// #swagger.description = 'One action rather than two, because there is no state in which you would want half of it: retry is legal only while the run is paused, and a paused run is paused AT this step. The step must be the one its phase is stopped at — a failed step under an `on_failure` of `skip` is one the run has already moved past, and re-queueing that would put a pending row behind the runner\'s cursor. `attempts` returns to zero: the attempt ceiling bounds what the runner does unattended, and a named person deciding is the thing it is unattended from.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The re-queued step and the run, with whether the resume took', content: { "application/json": { schema: { type: "object", properties: { step: { type: "object", additionalProperties: true }, run: { type: "object", additionalProperties: true }, resumed: { type: "boolean" } } } } } } */
/* #swagger.responses[404] = { description: 'No such run, or no such step on it', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'The run is not paused, or the run is not stopped at this step', content: { "application/json": { schema: { type: "object", properties: { errors: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Not an admin or moderator', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
liveControl,
controller.retryStep,
)
// ── Definitions ───────────────────────────────────────────────────────────
eventsRouter.get(