From cb5ff9a8585a217e6d576902b0a0fe82e03b78b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 11:28:41 +0000 Subject: [PATCH] refactor(plugin-approvals): move the approval service's timing constants and run-liveness tables to leaf modules Move-only: the reminder/SLA constants go to approval-service/sla-constants.ts and the run-liveness, strandability and stranded-continuation declarations to approval-service/run-liveness.ts; approval-service.ts imports them and re-exports every name it exported before. Claude-Session: https://claude.ai/code/session_01L9qibwUJvVPPjkmMrE42t7 Co-authored-by: Claude --- ...65-approval-service-run-liveness-module.md | 10 + .../plugin-approvals/src/approval-service.ts | 560 +----------------- .../src/approval-service/run-liveness.ts | 485 +++++++++++++++ .../src/approval-service/sla-constants.ts | 60 ++ 4 files changed, 586 insertions(+), 529 deletions(-) create mode 100644 .changeset/38665-approval-service-run-liveness-module.md create mode 100644 packages/plugins/plugin-approvals/src/approval-service/run-liveness.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-service/sla-constants.ts diff --git a/.changeset/38665-approval-service-run-liveness-module.md b/.changeset/38665-approval-service-run-liveness-module.md new file mode 100644 index 00000000000..b05a55a85b5 --- /dev/null +++ b/.changeset/38665-approval-service-run-liveness-module.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +refactor(plugin-approvals): the approval service's timing constants and run-liveness tables move to their own modules + +Clause-②: no +Metadata-protocol: none + +No behaviour change. The reminder and SLA-escalation constants (`REMIND_COOLDOWN_MS`, `ESCALATION_JOB_NAME`, `ESCALATION_SCAN_INTERVAL_MS`, `SLA_ACTOR_ID`, `ESCALATION_ENABLED_FLIP_CUTOFF_MS`) and the run-liveness and stranded-request tables and types (`RUN_STATUS_LIVENESS`, `REQUEST_STATUS_STRANDABILITY`, `StrandedRunState`, `StrandedApprovalRequest`, …) now live in modules of their own inside the package; the package exports the same names with the same values and types. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5401d18b3c8..9704f8e3042 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -8,9 +8,6 @@ import { canonicalApproverType, normalizeDecisionOutputs, type ApprovalNodeConfig, - // [#16433] The canonical run-status vocabulary, imported for its TYPE so the - // liveness classification below is checked against it member for member. - type ExecutionStatus, } from '@objectstack/spec/automation'; import { ExpressionEngine, @@ -201,12 +198,42 @@ import type { ApprovalServiceOptions, ApproverQueueSource, BatchLookup, - ConsumedSuspensionVerdict, ObjectReadAdmission, ObjectReadAdmissionSource, ResumeRefusal, SubflowParentStrandReport, } from './approval-service/options.js'; +import { + ESCALATION_ENABLED_FLIP_CUTOFF_MS, + REMIND_COOLDOWN_MS, + SLA_ACTOR_ID, +} from './approval-service/sla-constants.js'; +import { + type ApprovalContinuationResult, + classifyStrandedRunState, + CONTINUATIONS_A_STATUS_CAN_ISSUE, + refineFailedRunState, + STRANDABLE_REQUEST_STATUSES, + STRANDED_CONTINUATION_KEY, + type StrandedApprovalRequest, + type StrandedContinuationSignal, + type StrandedRunState, + TERMINAL_RUN_STATUSES, +} from './approval-service/run-liveness.js'; +export { RUN_STATUS_LIVENESS, REQUEST_STATUS_STRANDABILITY } from './approval-service/run-liveness.js'; +export type { + StrandedRunState, + StrandedContinuationSignal, + ApprovalContinuationResult, + StrandedApprovalRequest, +} from './approval-service/run-liveness.js'; +export { + REMIND_COOLDOWN_MS, + ESCALATION_JOB_NAME, + ESCALATION_SCAN_INTERVAL_MS, + SLA_ACTOR_ID, + ESCALATION_ENABLED_FLIP_CUTOFF_MS, +} from './approval-service/sla-constants.js'; // The collaborator surfaces and the options bag live in their own leaf module; // every name this file exported before is still exported from here. export type { @@ -298,531 +325,6 @@ type ApprovalNoticeInput = readonly keyedText?: never; }; -/** Minimum time between submitter reminders on one request. */ -export const REMIND_COOLDOWN_MS = 4 * 60 * 60 * 1000; - -/** Named job under which the SLA escalation scan is registered (ADR-0042). */ -export const ESCALATION_JOB_NAME = 'approvals-sla-escalation'; -/** Default interval between SLA escalation scans. */ -export const ESCALATION_SCAN_INTERVAL_MS = 5 * 60 * 1000; -/** - * The SLA sweep's ACTING identity — what it names as `actorId` when it - * auto-decides through `decide()` under {@link SYSTEM_CTX}, because the - * system-context arm of `resolveActor` requires an explicit actor. - * - * ⛔ It is never RECORDED. Every actor column the sweep writes — the - * `escalate` row, the auto-decision it then takes, `sys_notification.actor_id` - * through `notify` — is a `sys_user` lookup, and under ADR-0118 D1 such a - * column holds a user id or `null`, never a sentinel: a machine has no - * `sys_user` id, so it records `null` ({@link recordedActor}). That the sweep - * acted is the row's own kind (`escalate`, with the configured action in its - * comment), and its auto-decision is the `approve` / `reject` the same - * request records right after it. Rows stored before this rule carried this - * string in `actor_id`; the boot-time `backfillActionSlots` nulls them. - */ -export const SLA_ACTOR_ID = 'system:sla'; -/** - * Read-side legacy window for the #12278 `escalation.enabled` default flip - * (maintainer ruling 2026-08-27, Option C). - * - * Until the flip, `ApprovalEscalationSchema` declared `enabled` with - * `.default(false)` while this sweep never read the key — and the - * approval-node executor parses node config through that schema before - * `openNodeRequest` snapshots it onto the request row. Every request opened - * from a flow that OMITTED `enabled` therefore stores a MATERIALIZED - * `enabled: false` in `node_config_json`, byte-identical to an authored - * `false`, and every such stored row is escalating today (measured basis on - * the ruling: the console inspector cannot author a `timeoutHours` without - * toggling the switch on, so no stored `false + timeoutHours` row carries an - * enforceable off-intent that today's runtime honours). - * - * The sweep's `enabled === false ⇒ skip` gate below therefore applies only to - * snapshots created at/after this cutoff (written by post-flip code, where - * `false` survives the parse only when an author wrote it). Older snapshots - * keep today's behaviour — they escalate — and the window retires itself as - * those pending requests drain; no tenant row is ever rewritten. - * - * Known, deliberate bound (recorded on #12278): an install that upgrades LONG - * after this date has pending requests created between the cutoff and its - * upgrade whose materialized `false` post-dates the cutoff; those honour the - * declared off. The alternative (a per-install marker or a stored-data - * normalization) buys that edge back at the price of new machinery or tenant - * writes — both rejected as the more expensive option under the ruling's - * "pick the cheaper transition" instruction. - */ -export const ESCALATION_ENABLED_FLIP_CUTOFF_MS = Date.parse('2026-08-28T00:00:00Z'); -/** How the dead-run sweep must treat one `ExecutionStatus` member. */ -type RunLiveness = 'terminal' | 'live'; - -/** - * EVERY `ExecutionStatus` member (`@objectstack/spec`), classified for the - * dead-run sweep: `'terminal'` means the run has stopped and will never resume, - * so a request still pending on it is orphaned (#3456); `'live'` means it may - * still move, and the sweep must leave it strictly alone. - * - * ## Why a total MAP and not a list of the terminal ones (#16433) - * - * This was a hand-copied FOUR-member subset — `completed`, `failed`, - * `cancelled`, `timed_out` — written when `ExecutionStatus` had eight members - * and correct on the day it was written. #14945 then appended `refused` - * ("Terminal, never resumed"), and this subset did not grow with it: the sweep - * `continue`d past a refused run, so a pending approval on it read ALIVE and - * was never released. Nothing went red, because a subset that is missing a - * member is still a valid subset. - * - * ⚠️ Note what #14945's author DID do, directly above that member: *"Appended - * last so every reader that indexes `.options` keeps its positions."* That is a - * real precaution, taken with downstream readers genuinely in mind — but it - * protects readers that index the enum BY POSITION. **This reader hand-copied - * a subset, which lives by CONTENT, and position-safety does nothing for it.** - * ⇒ Enum-growth compatibility reasoning points naturally at order and index; - * the copies that rot are the ones keyed on membership, and they rot silently. - * - * So the repair is not "add `refused`" — that produces a five-member hand-copy - * with the identical trap re-armed for the tenth member. It is not "derive the - * terminal set from the enum" either: `running` and `paused` are obviously not - * terminal, and a wholesale derivation would make every FUTURE member terminal - * by default — the same silent default pointing the other way, and pointing at - * the worse outcome (releasing approvals out from under live runs). - * - * What this map is instead: a TOTAL function over the enum, so growth forces a - * decision. `satisfies Record` is exhaustive in - * both directions — a tenth member added to `ExecutionStatus` with no entry - * here fails to compile, and an entry for a member the enum dropped fails too. - * `run-status-liveness.test.ts` asserts the same totality at RUNTIME against - * `ExecutionStatus.options` and drives every member through the real sweep, so - * the classification and the behaviour cannot drift apart either. - * - * ⛔ Terminality is NOT declared machine-readably in the SPEC — `refused`'s - * terminality lives in a COMMENT beside the enum member, and a comment is not a - * gate. The `TERMINAL_RUN_STATUSES` exported by `@objectstack/service-automation` - * is a DIFFERENT vocabulary (which terminal states a run may be RECORDED in, - * tied to `sys_automation_run.status`' options), and that package is only a - * devDependency here. Hence a local total map rather than a shared import; see - * the card for the spec-level proposal. - * - * [#15788] That list used to exclude `refused` on purpose — nothing could write - * the value — and now includes it, because the `end` executor produces it. The - * two vocabularies AGREE about `refused` today; they are still not the same - * question, so this map stays the authority for THIS sweep. ⛔ Do not replace it - * with an import on the strength of one member currently matching. - * - * `completed` is classified terminal alongside the failure states. The approval - * node only writes a request row on the path where it also suspends the run, - * and every in-band transition (decide / recall / send-back / resubmit) - * finalises the request *before* it resumes the run — so a completed run with a - * still-pending request means the run was resumed out of band and left the - * request behind. - * - * `pending` / `running` / `paused` / `retrying` are live. `paused` especially: - * that is a run waiting on its own approval, the normal case. - */ -export const RUN_STATUS_LIVENESS = { - pending: 'live', // queued, has not started - running: 'live', // executing right now - paused: 'live', // parked at a wait/checkpoint — usually THIS approval - retrying: 'live', // failed and will run again - completed: 'terminal', // finished; a pending request means an out-of-band resume - failed: 'terminal', // terminated with an error - cancelled: 'terminal', // cancelled by hand - timed_out: 'terminal', // exceeded its budget - // [#14945 / #16433] The flow reached an `end` node declaring - // `outcome: 'refused'` — a successful evaluation that said no. The enum - // documents it "Terminal, never resumed"; this is that sentence made - // machine-readable for the one reader that has to act on it. - refused: 'terminal', - // A scheduled due time that passed while no kernel was ticking: recorded - // once, never started, never resumed. - missed: 'terminal', -} as const satisfies Record; - -/** - * Run statuses that mean "this run will never resume" — DERIVED from - * {@link RUN_STATUS_LIVENESS}, never re-typed (#16433). - * - * Still a closed set at the point of use, and deliberately so: the sweep treats - * every other answer — a live status, an unknown status, or no answer at all — - * as alive, so an unrecognised state can never cost someone a live approval. - */ -const TERMINAL_RUN_STATUSES: ReadonlySet = new Set( - Object.entries(RUN_STATUS_LIVENESS) - .filter(([, liveness]) => liveness === 'terminal') - .map(([status]) => status), -); - -/** Whether one {@link ApprovalStatus} can leave a zombie behind (#4469). */ -type RequestStrandability = 'strandable' | 'not-strandable'; - -/** - * EVERY {@link APPROVAL_STATUSES} member, classified for the stranded-request - * scan: `'strandable'` are the terminal states a decision reaches only by ALSO - * resuming the owning run (#4469), so a row sitting in one with its run still - * parked is a zombie. - * - * ## The same construction as {@link RUN_STATUS_LIVENESS}, for the same reason - * - * [#16433] This was the second hand-copied subset of a growing enum in this - * file, and the card that fixed the first one asked for a reading of it rather - * than an assumption. The reading: `APPROVAL_STATUSES` gained `cancelled` - * (#13568) AFTER this subset was written, and `cancelled` is correctly outside - * it — {@link ApprovalService.cancelForDeletedRecord} does NOT resume - * the run (it cancels it since #37763, and names any it could not cancel in - * its own `warn`), and reporting those here would bury the real findings - * under expected ones, exactly the `recalled` argument. ⇒ the VALUE was right; only the MECHANISM was the - * hand-copy, and nothing recorded that `cancelled` had been considered at all, - * so the next reader could not tell "weighed and excluded" from "written before - * it existed". - * - * The derived list below is byte-identical to the four-year-old literal - * (`['approved', 'rejected', 'returned']`, in that order, which the `$in` at - * the call site depends on). What changed is that a SEVENTH approval status now - * fails to compile until someone classifies it. - * - * `recalled` is deliberately not strandable: a recall ABANDONS the request on - * purpose, and {@link ApprovalService.recall} explicitly tolerates a run it - * cannot resume (the withdrawal and the lock release are the point). - * `pending` is not terminal at all. - */ -export const REQUEST_STATUS_STRANDABILITY = { - pending: 'not-strandable', // not terminal — still awaiting a decision - approved: 'strandable', // a decision that should have resumed the run - rejected: 'strandable', // idem - recalled: 'not-strandable', // deliberate abandonment; tolerates an unresumable run - returned: 'strandable', // send-back resumes down the `revise` edge - cancelled: 'not-strandable', // [#13568] platform void; never resumes (cancels the run, #37763) -} as const satisfies Record; - -/** - * The strandable statuses, DERIVED from {@link REQUEST_STATUS_STRANDABILITY} - * and never re-typed (#16433). Declaration order follows `APPROVAL_STATUSES`. - */ -const STRANDABLE_REQUEST_STATUSES: readonly ApprovalStatus[] = Object.entries( - REQUEST_STATUS_STRANDABILITY, -) - .filter(([, strandability]) => strandability === 'strandable') - .map(([status]) => status as ApprovalStatus); - -/** - * Where {@link ApprovalService.journalStrandedContinuation} keeps the signal a - * stranded resume carried (#15389), inside `node_config_json`. - * - * A private side-channel on an existing JSON column, exactly like - * `__decisionOutputs` beside it — not a new column and not authored node - * config. `parseJson` is a plain parse with no schema, and every reader of that - * JSON reads named fields, so an extra underscore key is inert for all of them. - */ -const STRANDED_CONTINUATION_KEY = '__strandedContinuation'; - -/** - * Which continuations a request's CURRENT status can have issued (#15389) — - * the compatibility the journal is checked against before it is replayed. - * - * ## Why the journal alone is not enough - * - * {@link STRANDED_CONTINUATION_KEY} records what the LAST failed resume was - * carrying. It is written when that resume strands and it is never rewritten by - * anything that moves the row on afterwards — so a signal can outlive the state - * that issued it. Measured, with no injected failure beyond the strand itself: - * a `resubmit` strands and journals `resubmit`; the submitter then recalls, and - * a real `cancelRun` on an already-stranded run answers `false`, so the recall - * marks the row `recalled` and leaves the run parked; `restoreConsumedSuspension` - * re-arms the pause; and the verb replays the stale `resubmit`, opening a fresh - * `pending` round on a request somebody deliberately withdrew — statuses - * `["recalled","pending"]`. Every step is an ordinary operator or submitter - * action answering ordinarily. - * - * ⛔ Clearing the journal after a successful replay does NOT close this: the - * offending replay is the FIRST replay of that journal, so a clear that fires - * after a replay succeeds can never run before the advance it would prevent. - * Measured — with such a clear in place, both limbs still reach `resumed: true`. - * The check has to happen BEFORE the journal is returned, which is where it is. - * - * ## Reading the table - * - * Each row is "what a row in this status can have issued", not "how many - * writers the status has" — the two are different questions and only this one - * gates a replay. `returned` carries two issuers by construction (`sendBack` - * writes it and resumes down `revise`; a later `resubmit` on that same row - * resumes down `resubmit` and writes NO status, so the row still reads - * `returned`), so both signals are compatible with it and the journal says - * which one actually stranded. `recalled` admits `recall` alone: a recall - * stranded by a build that HAS the journal replays exactly, and that is the one - * population a `recalled` row is replayable for. - * - * ⛔ A status absent from this table (`pending`, `cancelled`, anything new) - * admits NOTHING, deliberately: a status whose replayable continuations nobody - * has enumerated is not a status this verb may guess at. - */ -const CONTINUATIONS_A_STATUS_CAN_ISSUE: Readonly> = { - approved: ['approve'], - rejected: ['reject'], - returned: ['revise', 'resubmit'], - recalled: ['recall'], -}; - -/** - * The second oracle's verdict: which unrecoverable shape this run is in, or - * `undefined` for every run that must NOT be reported (#13909). - * - * Written as an explicit switch, not `status !== 'completed'`, because the - * negatives are the load-bearing half — a widening that reports everything the - * old `if (terminal) continue` used to skip would bury the finding it exists to - * surface. Each skip below is a distinct reason, and each is pinned by its own - * test. - * - * The engine writes exactly four run statuses (`paused`, `completed`, `failed`, - * `cancelled`); the spec's `ExecutionStatus` vocabulary is wider (`timed_out`, - * `retrying`, …) and nothing in the engine writes the rest today. The `default` - * arm therefore stays SILENT rather than reporting: a status this code does not - * recognise is not evidence a decision was stranded, and condemning on it would - * make every future status a false positive until someone noticed. - */ -function classifyStrandedRunState(run: { status?: string } | null | undefined): StrandedRunState | undefined { - // No history row at all — the #4469 shape this inspection was built for. - if (!run) return 'missing'; - switch (run.status) { - // A terminal `failed` row. Reported — and, when the engine can be asked, - // refined by the third oracle ({@link refineFailedRunState}) into which of - // the three `failed` shapes it is. This arm alone cannot tell them apart: - // the row reads identically for a resume that consumed the pause and - // threw downstream and for an ancestor `failAncestors` cascade-failed — - // and [#15222] which of THOSE is repairable is itself no longer decided by - // the shape: an ancestor whose descendant is repairable is journalled and - // re-armed with it. `'failed'` here means "reported, undifferentiated". - case 'failed': - return 'failed'; - - // ── The negatives, each for its own reason ────────────────────────────── - // The decision advanced the flow and the flow finished. Healthy. - case 'completed': - return undefined; - // Deliberately terminated by an operator (`cancelRun`, ADR-0044). The run - // stopping is the intended outcome, exactly as `recalled` is on the request - // side — reporting it would bury the real findings under expected ones. - case 'cancelled': - return undefined; - // The history's last row says `paused` while the suspension store says no - // live pause. That is AMBIGUOUS, and the ambiguity is not resolvable from - // one scan: a resume in flight right now has consumed the suspension and - // not yet written its terminal row, and reads exactly like a process that - // died in the same window. Condemning it would name every concurrently - // resuming approval — so this stays SKIPPED, the conservative arm this - // whole method is built on. - case 'paused': - return undefined; - default: - return undefined; - } -} - -/** - * [#15358] The third oracle's verdict over a `failed` row — which of the three - * differentiated shapes it is, read from the engine's own consumed-suspension - * witnesses — or `undefined` for the one answer that means the row is not - * stranded after all. - * - * ⛔ Absence of the discriminator is NOT an input here, on purpose: this runs - * only when the engine answered. A surface without the member never reaches - * it and the row stays `'failed'` (see {@link StrandedRunState}) — reading - * "the engine could not be asked" as "not a strand" would call the repairable - * row dead, which is #15555's false negative one surface over. - */ -function refineFailedRunState(verdict: ConsumedSuspensionVerdict): StrandedRunState | undefined { - if (verdict.repairable) return 'repairable'; - switch (verdict.reason) { - // The strand happened; the store could not keep the snapshot, and the - // engine asked holds no hot copy. Its own class — see the type below. - case 'SNAPSHOT_DROPPED': - return 'snapshot_dropped'; - // Neither witness holds anything: never paused, the snapshot is no longer - // held, or [#15222] a cascade whose own descendant was beyond repair — the - // one cascade shape that is still journalled nothing, deliberately, so the - // report never promises a chain repair that could not be completed. - case 'NO_CONSUMED_SUSPENSION': - return 'unrepairable'; - // Re-armed between the two reads (an operator's restore landed while this - // scan was running): the run is alive and resumable, which is what the - // first oracle would have said a moment later. Not stranded. - case 'RUN_SUSPENDED': - return undefined; - // An answer this build does not know (an engine ahead of this plugin). - // Fail-closed exactly as an absent member: reported, undifferentiated — - // never condemned on a word this code cannot read. - default: - return 'failed'; - } -} - -/** - * WHY a terminal request's run is unrecoverable — the shapes the inspection - * reports, which have different causes and different remedies (#13909; - * split three ways by the #15358 B′ ruling, 2026-09-07). - * - * - `missing` — `getRun` finds no history row at all (#4469's original shape): - * the run was lost before it could record anything, typically a pause that - * never reached a durable store and did not survive a restart. - * - * The other four all describe a run that DID record a terminal `failed` row. - * The engine consumes a suspension *before* running the downstream nodes - * (`AutomationEngine.resumeInternal`: `forgetSuspendedRun(run, 'resumed')` - * precedes `traverseNext`), so a downstream node that merely THREW threw with - * the pause already gone — the catch arm recorded `failed` and there is no - * suspension left to resume. The decision is durable and the flow stopped - * mid-continuation. What differs is whether anything can put the pause back, - * and `status` alone cannot say — the three differentiated members come from - * the engine's own consumed-suspension witnesses - * ({@link ApprovalResumeSurface.inspectConsumedSuspension}): - * - * - `repairable` — the engine holds the consumed suspension (in its journal - * or on the durable row): the #13909 strand. `restoreConsumedSuspension` - * re-arms it and {@link ApprovalService.continueRestoredRun} re-issues the - * decision. The remedy is a repair. - * - `snapshot_dropped` — the run DID strand, but the store could not persist - * the snapshot (over its row budget) and the engine asked holds no hot - * copy. Repairable only by the process that stranded it, while that process - * lives; the restore verb refuses it elsewhere naming the budget. ⛔ Not - * folded into either neighbour: as `repairable` it over-reports, as - * `unrepairable` it is #15555's false negative. Reported as what it is. - * - `unrepairable` — the engine holds NO consumed suspension: the run never - * paused at all; or it did strand and its snapshot is no longer held (the - * journal evicted a copy whose write never landed; the run was restored and - * then finished; a store class without `loadTerminal`, after a restart); or - * it was cascade-failed by a descendant that was ITSELF beyond repair — - * the engine's `NO_CONSUMED_SUSPENSION` covers all three and does not say - * which. The label is faithful to the verb: nothing re-arms it; the remedy - * is a new run, not a restore. - * ⚠️ [#15222] A cascade-failed ancestor is NOT this label by default any - * more. `failSuspendedRun` journals the pause it consumes whenever the - * descendant that cascaded into it is repairable, and the restore verb - * re-arms leaf and ancestors as one unit — so those ancestors report - * `repairable`, and restoring any member of the chain repairs all of it. - * - `failed` — the engine COULD NOT BE ASKED which of the three it is, or - * was asked and could not answer. Three ways in: the attached surface has - * no `inspectConsumedSuspension` (an engine build older than this plugin, - * or a test double); the read THREW (a store outage); or the host resolved - * a malformed verdict, violating its own declared surface (commit 8c7cca1ce). Today's - * undifferentiated label, kept on purpose as the fail-closed fallback - * (#15358 ruling, item 1): a failure to differentiate is not evidence, so - * the row is reported and its repairability left unstated — ⛔ never - * `unrepairable`, ⛔ never dropped from the report. - * - * ⚠️ This names the shapes for the REPORT only. It is not a run state: the - * engine's own vocabulary is still `'completed' | 'paused' | 'failed'` - * (`AutomationResult.status`) and nothing persists or queries "stranded". - * Giving the condition a platform-level name is #13909's own deliverable. - */ -export type StrandedRunState = 'missing' | 'failed' | 'repairable' | 'snapshot_dropped' | 'unrepairable'; - -/** - * The continuation an approvals door already issued once, kept so it can be - * issued AGAIN after an operator re-arms the pause it was refused on (#15389). - * - * Stashed under `__strandedContinuation` in `sys_approval_request` - * `node_config_json` — the same private side-channel `__decisionOutputs` - * already uses, rather than a new column: this is recovery bookkeeping for a - * rare failure path, not part of the authored node config, and every reader of - * that JSON reads named fields. - */ -export interface StrandedContinuationSignal { - /** The `approve` / `reject` / `revise` / `resubmit` edge the outcome walks. */ - branchLabel?: string; - /** The exact flow-variable payload the original resume carried. */ - output?: Record; - /** Outcome label for the {@link strandedDecisionFailure} envelope. */ - decision: string; - /** How the original door described the outcome in prose, e.g. `the reject decision`. */ - what: string; - /** - * The decider the original resume carried ({@link ApprovalResumeSurface}'s - * `resumedBy`), so a replay continues the nodes after the decision as the - * person who decided, never as the run's trigger user. Absent when the - * original carried none. - */ - resumedBy?: string; - /** - * The administrator the original resume named as impersonating - * {@link resumedBy} (`ResumeSignal.impersonatedBy`), so a replay stamps the - * decider's segment exactly as the decision did. Absent when the original - * carried none. - */ - impersonatedBy?: string; -} - -/** - * Outcome of {@link ApprovalService.continueRestoredRun} (#15389). - * - * ⚠️ Deliberately its own shape rather than a reuse of `ApprovalDecisionResult`: - * the #16472 family ruling settled that contract for `decide` (#15556) and - * `recall` (#15970) by name, and this repair-replay verb is neither of those - * doors — reusing their shape here would answer a question nobody asked. - * Nothing here changes what `decide` answers. - */ -export interface ApprovalContinuationResult { - /** True when the restored pause was consumed and the flow moved on. */ - resumed: boolean; - /** The run this continued — the one the request has always named. */ - runId: string; - /** The outcome that was replayed, exactly as it was first recorded. */ - decision: string; - /** The edge it walked. */ - branchLabel?: string; - /** - * Where the replayed signal came from, so a caller can tell an EXACT replay - * from an inferred one: - * - * - `journal` — the failing door stashed the literal signal it sent, so this - * is a byte-for-byte re-issue. - * - `reconstructed` — no stash (the strand predates that journalling, or its - * write failed), so the signal was rebuilt from the row's recorded outcome. - * Exact for every status this verb accepts; the one shape it CANNOT rebuild - * is refused rather than guessed (see the method's `AMBIGUOUS_RECORDED_OUTCOME`). - */ - source: 'journal' | 'reconstructed'; - /** Set only on the tolerated non-failure: a concurrent resume already had it. */ - resumeError?: string; -} - -/** - * One terminal request whose owning flow run is unrecoverable (#4469) — the - * decision was recorded and the flow never moved. Reporting shape only: the - * sweep never rewrites these rows (see - * {@link ApprovalService.inspectStrandedRequests}). - */ -export interface StrandedApprovalRequest { - requestId: string; - /** Terminal status the request reached — the decision that WAS recorded. */ - status: string; - /** - * The `flow_run_id` that resolves to no live suspension and no recoverable - * run — see `runState`: no history row at all (`missing`), or a terminal - * `failed` row (`repairable` / `snapshot_dropped` / `unrepairable`, or - * `failed` when the engine could not say which). - */ - runId: string; - /** - * Which unrecoverable shape this is — see {@link StrandedRunState}. Carried - * because the shapes need different remedies: a `missing` run has no history - * to read; a `repairable` one is put back by `restoreConsumedSuspension` and - * continued by {@link ApprovalService.continueRestoredRun} — and [#15222] - * that restore re-arms every run of a nested chain, so a `repairable` row - * may be repaired by restoring a DIFFERENT row of the same tree; an - * `unrepairable` one is refused by that verb and needs a new run. An - * operator reading `'failed'` has to ask the engine directly. - */ - runState: StrandedRunState; - flowName?: string; - /** Approval node the run should have continued from. */ - nodeId?: string; - objectName: string; - recordId: string; - organizationId?: string | null; - completedAt?: string; - /** `config.approvalStatusField`, when the node mirrors status onto the record. */ - mirrorField?: string; - /** What that mirror field currently reads — usually the stale value an operator sees. */ - mirroredStatus?: string; -} - /** Default lifetime of an actionable-link token (ADR-0043). */ export const ACTION_TOKEN_TTL_MS = 72 * 60 * 60 * 1000; diff --git a/packages/plugins/plugin-approvals/src/approval-service/run-liveness.ts b/packages/plugins/plugin-approvals/src/approval-service/run-liveness.ts new file mode 100644 index 00000000000..644d3da130c --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-service/run-liveness.ts @@ -0,0 +1,485 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +// Run liveness and request strandability: how the approval service classifies +// a flow run's status and a request's status when it decides whether a request +// is stranded, and the shapes the stranded-request inspection and the restored +// continuation answer with. A leaf module: it imports nothing from +// `../approval-service.ts`, which re-exports every name here it exported before. + +// [#16433] The canonical run-status vocabulary, imported for its TYPE so the +// liveness classification below is checked against it member for member. +import type { ExecutionStatus } from '@objectstack/spec/automation'; +import type { ApprovalStatus } from '@objectstack/spec/contracts'; +import type { ConsumedSuspensionVerdict } from './options.js'; + +/** How the dead-run sweep must treat one `ExecutionStatus` member. */ +type RunLiveness = 'terminal' | 'live'; + +/** + * EVERY `ExecutionStatus` member (`@objectstack/spec`), classified for the + * dead-run sweep: `'terminal'` means the run has stopped and will never resume, + * so a request still pending on it is orphaned (#3456); `'live'` means it may + * still move, and the sweep must leave it strictly alone. + * + * ## Why a total MAP and not a list of the terminal ones (#16433) + * + * This was a hand-copied FOUR-member subset — `completed`, `failed`, + * `cancelled`, `timed_out` — written when `ExecutionStatus` had eight members + * and correct on the day it was written. #14945 then appended `refused` + * ("Terminal, never resumed"), and this subset did not grow with it: the sweep + * `continue`d past a refused run, so a pending approval on it read ALIVE and + * was never released. Nothing went red, because a subset that is missing a + * member is still a valid subset. + * + * ⚠️ Note what #14945's author DID do, directly above that member: *"Appended + * last so every reader that indexes `.options` keeps its positions."* That is a + * real precaution, taken with downstream readers genuinely in mind — but it + * protects readers that index the enum BY POSITION. **This reader hand-copied + * a subset, which lives by CONTENT, and position-safety does nothing for it.** + * ⇒ Enum-growth compatibility reasoning points naturally at order and index; + * the copies that rot are the ones keyed on membership, and they rot silently. + * + * So the repair is not "add `refused`" — that produces a five-member hand-copy + * with the identical trap re-armed for the tenth member. It is not "derive the + * terminal set from the enum" either: `running` and `paused` are obviously not + * terminal, and a wholesale derivation would make every FUTURE member terminal + * by default — the same silent default pointing the other way, and pointing at + * the worse outcome (releasing approvals out from under live runs). + * + * What this map is instead: a TOTAL function over the enum, so growth forces a + * decision. `satisfies Record` is exhaustive in + * both directions — a tenth member added to `ExecutionStatus` with no entry + * here fails to compile, and an entry for a member the enum dropped fails too. + * `run-status-liveness.test.ts` asserts the same totality at RUNTIME against + * `ExecutionStatus.options` and drives every member through the real sweep, so + * the classification and the behaviour cannot drift apart either. + * + * ⛔ Terminality is NOT declared machine-readably in the SPEC — `refused`'s + * terminality lives in a COMMENT beside the enum member, and a comment is not a + * gate. The `TERMINAL_RUN_STATUSES` exported by `@objectstack/service-automation` + * is a DIFFERENT vocabulary (which terminal states a run may be RECORDED in, + * tied to `sys_automation_run.status`' options), and that package is only a + * devDependency here. Hence a local total map rather than a shared import; see + * the card for the spec-level proposal. + * + * [#15788] That list used to exclude `refused` on purpose — nothing could write + * the value — and now includes it, because the `end` executor produces it. The + * two vocabularies AGREE about `refused` today; they are still not the same + * question, so this map stays the authority for THIS sweep. ⛔ Do not replace it + * with an import on the strength of one member currently matching. + * + * `completed` is classified terminal alongside the failure states. The approval + * node only writes a request row on the path where it also suspends the run, + * and every in-band transition (decide / recall / send-back / resubmit) + * finalises the request *before* it resumes the run — so a completed run with a + * still-pending request means the run was resumed out of band and left the + * request behind. + * + * `pending` / `running` / `paused` / `retrying` are live. `paused` especially: + * that is a run waiting on its own approval, the normal case. + */ +export const RUN_STATUS_LIVENESS = { + pending: 'live', // queued, has not started + running: 'live', // executing right now + paused: 'live', // parked at a wait/checkpoint — usually THIS approval + retrying: 'live', // failed and will run again + completed: 'terminal', // finished; a pending request means an out-of-band resume + failed: 'terminal', // terminated with an error + cancelled: 'terminal', // cancelled by hand + timed_out: 'terminal', // exceeded its budget + // [#14945 / #16433] The flow reached an `end` node declaring + // `outcome: 'refused'` — a successful evaluation that said no. The enum + // documents it "Terminal, never resumed"; this is that sentence made + // machine-readable for the one reader that has to act on it. + refused: 'terminal', + // A scheduled due time that passed while no kernel was ticking: recorded + // once, never started, never resumed. + missed: 'terminal', +} as const satisfies Record; + +/** + * Run statuses that mean "this run will never resume" — DERIVED from + * {@link RUN_STATUS_LIVENESS}, never re-typed (#16433). + * + * Still a closed set at the point of use, and deliberately so: the sweep treats + * every other answer — a live status, an unknown status, or no answer at all — + * as alive, so an unrecognised state can never cost someone a live approval. + */ +export const TERMINAL_RUN_STATUSES: ReadonlySet = new Set( + Object.entries(RUN_STATUS_LIVENESS) + .filter(([, liveness]) => liveness === 'terminal') + .map(([status]) => status), +); + +/** Whether one {@link ApprovalStatus} can leave a zombie behind (#4469). */ +type RequestStrandability = 'strandable' | 'not-strandable'; + +/** + * EVERY {@link APPROVAL_STATUSES} member, classified for the stranded-request + * scan: `'strandable'` are the terminal states a decision reaches only by ALSO + * resuming the owning run (#4469), so a row sitting in one with its run still + * parked is a zombie. + * + * ## The same construction as {@link RUN_STATUS_LIVENESS}, for the same reason + * + * [#16433] This was the second hand-copied subset of a growing enum in this + * file, and the card that fixed the first one asked for a reading of it rather + * than an assumption. The reading: `APPROVAL_STATUSES` gained `cancelled` + * (#13568) AFTER this subset was written, and `cancelled` is correctly outside + * it — {@link ApprovalService.cancelForDeletedRecord} does NOT resume + * the run (it cancels it since #37763, and names any it could not cancel in + * its own `warn`), and reporting those here would bury the real findings + * under expected ones, exactly the `recalled` argument. ⇒ the VALUE was right; only the MECHANISM was the + * hand-copy, and nothing recorded that `cancelled` had been considered at all, + * so the next reader could not tell "weighed and excluded" from "written before + * it existed". + * + * The derived list below is byte-identical to the four-year-old literal + * (`['approved', 'rejected', 'returned']`, in that order, which the `$in` at + * the call site depends on). What changed is that a SEVENTH approval status now + * fails to compile until someone classifies it. + * + * `recalled` is deliberately not strandable: a recall ABANDONS the request on + * purpose, and {@link ApprovalService.recall} explicitly tolerates a run it + * cannot resume (the withdrawal and the lock release are the point). + * `pending` is not terminal at all. + */ +export const REQUEST_STATUS_STRANDABILITY = { + pending: 'not-strandable', // not terminal — still awaiting a decision + approved: 'strandable', // a decision that should have resumed the run + rejected: 'strandable', // idem + recalled: 'not-strandable', // deliberate abandonment; tolerates an unresumable run + returned: 'strandable', // send-back resumes down the `revise` edge + cancelled: 'not-strandable', // [#13568] platform void; never resumes (cancels the run, #37763) +} as const satisfies Record; + +/** + * The strandable statuses, DERIVED from {@link REQUEST_STATUS_STRANDABILITY} + * and never re-typed (#16433). Declaration order follows `APPROVAL_STATUSES`. + */ +export const STRANDABLE_REQUEST_STATUSES: readonly ApprovalStatus[] = Object.entries( + REQUEST_STATUS_STRANDABILITY, +) + .filter(([, strandability]) => strandability === 'strandable') + .map(([status]) => status as ApprovalStatus); + +/** + * Where {@link ApprovalService.journalStrandedContinuation} keeps the signal a + * stranded resume carried (#15389), inside `node_config_json`. + * + * A private side-channel on an existing JSON column, exactly like + * `__decisionOutputs` beside it — not a new column and not authored node + * config. `parseJson` is a plain parse with no schema, and every reader of that + * JSON reads named fields, so an extra underscore key is inert for all of them. + */ +export const STRANDED_CONTINUATION_KEY = '__strandedContinuation'; + +/** + * Which continuations a request's CURRENT status can have issued (#15389) — + * the compatibility the journal is checked against before it is replayed. + * + * ## Why the journal alone is not enough + * + * {@link STRANDED_CONTINUATION_KEY} records what the LAST failed resume was + * carrying. It is written when that resume strands and it is never rewritten by + * anything that moves the row on afterwards — so a signal can outlive the state + * that issued it. Measured, with no injected failure beyond the strand itself: + * a `resubmit` strands and journals `resubmit`; the submitter then recalls, and + * a real `cancelRun` on an already-stranded run answers `false`, so the recall + * marks the row `recalled` and leaves the run parked; `restoreConsumedSuspension` + * re-arms the pause; and the verb replays the stale `resubmit`, opening a fresh + * `pending` round on a request somebody deliberately withdrew — statuses + * `["recalled","pending"]`. Every step is an ordinary operator or submitter + * action answering ordinarily. + * + * ⛔ Clearing the journal after a successful replay does NOT close this: the + * offending replay is the FIRST replay of that journal, so a clear that fires + * after a replay succeeds can never run before the advance it would prevent. + * Measured — with such a clear in place, both limbs still reach `resumed: true`. + * The check has to happen BEFORE the journal is returned, which is where it is. + * + * ## Reading the table + * + * Each row is "what a row in this status can have issued", not "how many + * writers the status has" — the two are different questions and only this one + * gates a replay. `returned` carries two issuers by construction (`sendBack` + * writes it and resumes down `revise`; a later `resubmit` on that same row + * resumes down `resubmit` and writes NO status, so the row still reads + * `returned`), so both signals are compatible with it and the journal says + * which one actually stranded. `recalled` admits `recall` alone: a recall + * stranded by a build that HAS the journal replays exactly, and that is the one + * population a `recalled` row is replayable for. + * + * ⛔ A status absent from this table (`pending`, `cancelled`, anything new) + * admits NOTHING, deliberately: a status whose replayable continuations nobody + * has enumerated is not a status this verb may guess at. + */ +export const CONTINUATIONS_A_STATUS_CAN_ISSUE: Readonly> = { + approved: ['approve'], + rejected: ['reject'], + returned: ['revise', 'resubmit'], + recalled: ['recall'], +}; + +/** + * The second oracle's verdict: which unrecoverable shape this run is in, or + * `undefined` for every run that must NOT be reported (#13909). + * + * Written as an explicit switch, not `status !== 'completed'`, because the + * negatives are the load-bearing half — a widening that reports everything the + * old `if (terminal) continue` used to skip would bury the finding it exists to + * surface. Each skip below is a distinct reason, and each is pinned by its own + * test. + * + * The engine writes exactly four run statuses (`paused`, `completed`, `failed`, + * `cancelled`); the spec's `ExecutionStatus` vocabulary is wider (`timed_out`, + * `retrying`, …) and nothing in the engine writes the rest today. The `default` + * arm therefore stays SILENT rather than reporting: a status this code does not + * recognise is not evidence a decision was stranded, and condemning on it would + * make every future status a false positive until someone noticed. + */ +export function classifyStrandedRunState(run: { status?: string } | null | undefined): StrandedRunState | undefined { + // No history row at all — the #4469 shape this inspection was built for. + if (!run) return 'missing'; + switch (run.status) { + // A terminal `failed` row. Reported — and, when the engine can be asked, + // refined by the third oracle ({@link refineFailedRunState}) into which of + // the three `failed` shapes it is. This arm alone cannot tell them apart: + // the row reads identically for a resume that consumed the pause and + // threw downstream and for an ancestor `failAncestors` cascade-failed — + // and [#15222] which of THOSE is repairable is itself no longer decided by + // the shape: an ancestor whose descendant is repairable is journalled and + // re-armed with it. `'failed'` here means "reported, undifferentiated". + case 'failed': + return 'failed'; + + // ── The negatives, each for its own reason ────────────────────────────── + // The decision advanced the flow and the flow finished. Healthy. + case 'completed': + return undefined; + // Deliberately terminated by an operator (`cancelRun`, ADR-0044). The run + // stopping is the intended outcome, exactly as `recalled` is on the request + // side — reporting it would bury the real findings under expected ones. + case 'cancelled': + return undefined; + // The history's last row says `paused` while the suspension store says no + // live pause. That is AMBIGUOUS, and the ambiguity is not resolvable from + // one scan: a resume in flight right now has consumed the suspension and + // not yet written its terminal row, and reads exactly like a process that + // died in the same window. Condemning it would name every concurrently + // resuming approval — so this stays SKIPPED, the conservative arm this + // whole method is built on. + case 'paused': + return undefined; + default: + return undefined; + } +} + +/** + * [#15358] The third oracle's verdict over a `failed` row — which of the three + * differentiated shapes it is, read from the engine's own consumed-suspension + * witnesses — or `undefined` for the one answer that means the row is not + * stranded after all. + * + * ⛔ Absence of the discriminator is NOT an input here, on purpose: this runs + * only when the engine answered. A surface without the member never reaches + * it and the row stays `'failed'` (see {@link StrandedRunState}) — reading + * "the engine could not be asked" as "not a strand" would call the repairable + * row dead, which is #15555's false negative one surface over. + */ +export function refineFailedRunState(verdict: ConsumedSuspensionVerdict): StrandedRunState | undefined { + if (verdict.repairable) return 'repairable'; + switch (verdict.reason) { + // The strand happened; the store could not keep the snapshot, and the + // engine asked holds no hot copy. Its own class — see the type below. + case 'SNAPSHOT_DROPPED': + return 'snapshot_dropped'; + // Neither witness holds anything: never paused, the snapshot is no longer + // held, or [#15222] a cascade whose own descendant was beyond repair — the + // one cascade shape that is still journalled nothing, deliberately, so the + // report never promises a chain repair that could not be completed. + case 'NO_CONSUMED_SUSPENSION': + return 'unrepairable'; + // Re-armed between the two reads (an operator's restore landed while this + // scan was running): the run is alive and resumable, which is what the + // first oracle would have said a moment later. Not stranded. + case 'RUN_SUSPENDED': + return undefined; + // An answer this build does not know (an engine ahead of this plugin). + // Fail-closed exactly as an absent member: reported, undifferentiated — + // never condemned on a word this code cannot read. + default: + return 'failed'; + } +} + +/** + * WHY a terminal request's run is unrecoverable — the shapes the inspection + * reports, which have different causes and different remedies (#13909; + * split three ways by the #15358 B′ ruling, 2026-09-07). + * + * - `missing` — `getRun` finds no history row at all (#4469's original shape): + * the run was lost before it could record anything, typically a pause that + * never reached a durable store and did not survive a restart. + * + * The other four all describe a run that DID record a terminal `failed` row. + * The engine consumes a suspension *before* running the downstream nodes + * (`AutomationEngine.resumeInternal`: `forgetSuspendedRun(run, 'resumed')` + * precedes `traverseNext`), so a downstream node that merely THREW threw with + * the pause already gone — the catch arm recorded `failed` and there is no + * suspension left to resume. The decision is durable and the flow stopped + * mid-continuation. What differs is whether anything can put the pause back, + * and `status` alone cannot say — the three differentiated members come from + * the engine's own consumed-suspension witnesses + * ({@link ApprovalResumeSurface.inspectConsumedSuspension}): + * + * - `repairable` — the engine holds the consumed suspension (in its journal + * or on the durable row): the #13909 strand. `restoreConsumedSuspension` + * re-arms it and {@link ApprovalService.continueRestoredRun} re-issues the + * decision. The remedy is a repair. + * - `snapshot_dropped` — the run DID strand, but the store could not persist + * the snapshot (over its row budget) and the engine asked holds no hot + * copy. Repairable only by the process that stranded it, while that process + * lives; the restore verb refuses it elsewhere naming the budget. ⛔ Not + * folded into either neighbour: as `repairable` it over-reports, as + * `unrepairable` it is #15555's false negative. Reported as what it is. + * - `unrepairable` — the engine holds NO consumed suspension: the run never + * paused at all; or it did strand and its snapshot is no longer held (the + * journal evicted a copy whose write never landed; the run was restored and + * then finished; a store class without `loadTerminal`, after a restart); or + * it was cascade-failed by a descendant that was ITSELF beyond repair — + * the engine's `NO_CONSUMED_SUSPENSION` covers all three and does not say + * which. The label is faithful to the verb: nothing re-arms it; the remedy + * is a new run, not a restore. + * ⚠️ [#15222] A cascade-failed ancestor is NOT this label by default any + * more. `failSuspendedRun` journals the pause it consumes whenever the + * descendant that cascaded into it is repairable, and the restore verb + * re-arms leaf and ancestors as one unit — so those ancestors report + * `repairable`, and restoring any member of the chain repairs all of it. + * - `failed` — the engine COULD NOT BE ASKED which of the three it is, or + * was asked and could not answer. Three ways in: the attached surface has + * no `inspectConsumedSuspension` (an engine build older than this plugin, + * or a test double); the read THREW (a store outage); or the host resolved + * a malformed verdict, violating its own declared surface (commit 8c7cca1ce). Today's + * undifferentiated label, kept on purpose as the fail-closed fallback + * (#15358 ruling, item 1): a failure to differentiate is not evidence, so + * the row is reported and its repairability left unstated — ⛔ never + * `unrepairable`, ⛔ never dropped from the report. + * + * ⚠️ This names the shapes for the REPORT only. It is not a run state: the + * engine's own vocabulary is still `'completed' | 'paused' | 'failed'` + * (`AutomationResult.status`) and nothing persists or queries "stranded". + * Giving the condition a platform-level name is #13909's own deliverable. + */ +export type StrandedRunState = 'missing' | 'failed' | 'repairable' | 'snapshot_dropped' | 'unrepairable'; + +/** + * The continuation an approvals door already issued once, kept so it can be + * issued AGAIN after an operator re-arms the pause it was refused on (#15389). + * + * Stashed under `__strandedContinuation` in `sys_approval_request` + * `node_config_json` — the same private side-channel `__decisionOutputs` + * already uses, rather than a new column: this is recovery bookkeeping for a + * rare failure path, not part of the authored node config, and every reader of + * that JSON reads named fields. + */ +export interface StrandedContinuationSignal { + /** The `approve` / `reject` / `revise` / `resubmit` edge the outcome walks. */ + branchLabel?: string; + /** The exact flow-variable payload the original resume carried. */ + output?: Record; + /** Outcome label for the {@link strandedDecisionFailure} envelope. */ + decision: string; + /** How the original door described the outcome in prose, e.g. `the reject decision`. */ + what: string; + /** + * The decider the original resume carried ({@link ApprovalResumeSurface}'s + * `resumedBy`), so a replay continues the nodes after the decision as the + * person who decided, never as the run's trigger user. Absent when the + * original carried none. + */ + resumedBy?: string; + /** + * The administrator the original resume named as impersonating + * {@link resumedBy} (`ResumeSignal.impersonatedBy`), so a replay stamps the + * decider's segment exactly as the decision did. Absent when the original + * carried none. + */ + impersonatedBy?: string; +} + +/** + * Outcome of {@link ApprovalService.continueRestoredRun} (#15389). + * + * ⚠️ Deliberately its own shape rather than a reuse of `ApprovalDecisionResult`: + * the #16472 family ruling settled that contract for `decide` (#15556) and + * `recall` (#15970) by name, and this repair-replay verb is neither of those + * doors — reusing their shape here would answer a question nobody asked. + * Nothing here changes what `decide` answers. + */ +export interface ApprovalContinuationResult { + /** True when the restored pause was consumed and the flow moved on. */ + resumed: boolean; + /** The run this continued — the one the request has always named. */ + runId: string; + /** The outcome that was replayed, exactly as it was first recorded. */ + decision: string; + /** The edge it walked. */ + branchLabel?: string; + /** + * Where the replayed signal came from, so a caller can tell an EXACT replay + * from an inferred one: + * + * - `journal` — the failing door stashed the literal signal it sent, so this + * is a byte-for-byte re-issue. + * - `reconstructed` — no stash (the strand predates that journalling, or its + * write failed), so the signal was rebuilt from the row's recorded outcome. + * Exact for every status this verb accepts; the one shape it CANNOT rebuild + * is refused rather than guessed (see the method's `AMBIGUOUS_RECORDED_OUTCOME`). + */ + source: 'journal' | 'reconstructed'; + /** Set only on the tolerated non-failure: a concurrent resume already had it. */ + resumeError?: string; +} + +/** + * One terminal request whose owning flow run is unrecoverable (#4469) — the + * decision was recorded and the flow never moved. Reporting shape only: the + * sweep never rewrites these rows (see + * {@link ApprovalService.inspectStrandedRequests}). + */ +export interface StrandedApprovalRequest { + requestId: string; + /** Terminal status the request reached — the decision that WAS recorded. */ + status: string; + /** + * The `flow_run_id` that resolves to no live suspension and no recoverable + * run — see `runState`: no history row at all (`missing`), or a terminal + * `failed` row (`repairable` / `snapshot_dropped` / `unrepairable`, or + * `failed` when the engine could not say which). + */ + runId: string; + /** + * Which unrecoverable shape this is — see {@link StrandedRunState}. Carried + * because the shapes need different remedies: a `missing` run has no history + * to read; a `repairable` one is put back by `restoreConsumedSuspension` and + * continued by {@link ApprovalService.continueRestoredRun} — and [#15222] + * that restore re-arms every run of a nested chain, so a `repairable` row + * may be repaired by restoring a DIFFERENT row of the same tree; an + * `unrepairable` one is refused by that verb and needs a new run. An + * operator reading `'failed'` has to ask the engine directly. + */ + runState: StrandedRunState; + flowName?: string; + /** Approval node the run should have continued from. */ + nodeId?: string; + objectName: string; + recordId: string; + organizationId?: string | null; + completedAt?: string; + /** `config.approvalStatusField`, when the node mirrors status onto the record. */ + mirrorField?: string; + /** What that mirror field currently reads — usually the stale value an operator sees. */ + mirroredStatus?: string; +} diff --git a/packages/plugins/plugin-approvals/src/approval-service/sla-constants.ts b/packages/plugins/plugin-approvals/src/approval-service/sla-constants.ts new file mode 100644 index 00000000000..6da62e35613 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-service/sla-constants.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +// The timing constants of the approval service: the reminder cooldown, the SLA +// escalation job's name, interval and acting identity, and the cutoff that +// gates the escalation-enabled flip. A leaf module: it imports nothing from +// `../approval-service.ts`, which re-exports every name here. + +/** Minimum time between submitter reminders on one request. */ +export const REMIND_COOLDOWN_MS = 4 * 60 * 60 * 1000; + +/** Named job under which the SLA escalation scan is registered (ADR-0042). */ +export const ESCALATION_JOB_NAME = 'approvals-sla-escalation'; +/** Default interval between SLA escalation scans. */ +export const ESCALATION_SCAN_INTERVAL_MS = 5 * 60 * 1000; +/** + * The SLA sweep's ACTING identity — what it names as `actorId` when it + * auto-decides through `decide()` under {@link SYSTEM_CTX}, because the + * system-context arm of `resolveActor` requires an explicit actor. + * + * ⛔ It is never RECORDED. Every actor column the sweep writes — the + * `escalate` row, the auto-decision it then takes, `sys_notification.actor_id` + * through `notify` — is a `sys_user` lookup, and under ADR-0118 D1 such a + * column holds a user id or `null`, never a sentinel: a machine has no + * `sys_user` id, so it records `null` ({@link recordedActor}). That the sweep + * acted is the row's own kind (`escalate`, with the configured action in its + * comment), and its auto-decision is the `approve` / `reject` the same + * request records right after it. Rows stored before this rule carried this + * string in `actor_id`; the boot-time `backfillActionSlots` nulls them. + */ +export const SLA_ACTOR_ID = 'system:sla'; +/** + * Read-side legacy window for the #12278 `escalation.enabled` default flip + * (maintainer ruling 2026-08-27, Option C). + * + * Until the flip, `ApprovalEscalationSchema` declared `enabled` with + * `.default(false)` while this sweep never read the key — and the + * approval-node executor parses node config through that schema before + * `openNodeRequest` snapshots it onto the request row. Every request opened + * from a flow that OMITTED `enabled` therefore stores a MATERIALIZED + * `enabled: false` in `node_config_json`, byte-identical to an authored + * `false`, and every such stored row is escalating today (measured basis on + * the ruling: the console inspector cannot author a `timeoutHours` without + * toggling the switch on, so no stored `false + timeoutHours` row carries an + * enforceable off-intent that today's runtime honours). + * + * The sweep's `enabled === false ⇒ skip` gate below therefore applies only to + * snapshots created at/after this cutoff (written by post-flip code, where + * `false` survives the parse only when an author wrote it). Older snapshots + * keep today's behaviour — they escalate — and the window retires itself as + * those pending requests drain; no tenant row is ever rewritten. + * + * Known, deliberate bound (recorded on #12278): an install that upgrades LONG + * after this date has pending requests created between the cutoff and its + * upgrade whose materialized `false` post-dates the cutoff; those honour the + * declared off. The alternative (a per-install marker or a stored-data + * normalization) buys that edge back at the price of new machinery or tenant + * writes — both rejected as the more expensive option under the ruling's + * "pick the cheaper transition" instruction. + */ +export const ESCALATION_ENABLED_FLIP_CUTOFF_MS = Date.parse('2026-08-28T00:00:00Z');