diff --git a/.changeset/37766-abandoned-mirror.md b/.changeset/37766-abandoned-mirror.md new file mode 100644 index 00000000000..5836107f822 --- /dev/null +++ b/.changeset/37766-abandoned-mirror.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): an abandoned approval never writes a closed value on its status mirror (ADR-0162 D5, Execution item 7) + +Clause-②: no +Metadata-protocol: none + +A request is abandoned by its submitter's recall (while it is pending, or in the revise window after a send-back), by the override arm of a recall (an administrator, or a system context), and by the sweep that releases a record held by a dead run. Each puts a value back on the field the approval mirrors its status onto. Where the object's `closedStates` lists any value for that field (ADR-0162 D1), the mirror now chooses that value so that it never closes the document again: + +- **`recalled`** is written where the field declares it and the object does not close on it, as before. A declared `recalled` the object closes on is withheld, and a `warn` line says so: listing `recalled` among the closed values closes nothing through the mirror. +- **Otherwise the order**: the value held at submit, the field's declared default, empty. A closed value is passed over at each step, and on a required field an empty value at submit is passed over for the default. A pass is logged at `info`. +- **A closed value the approval did not write is left alone.** Where the field holds a closed value, the mirror asks the request table once, by the request's root run and record, whether a request of the same approval on the same record had that value as its status. Where none did, it writes nothing and logs it at `info`. A request of the approval on another record (another item of a `map`) does not count. Where it cannot tell (the request records no root run, or a request on the record that records none was opened since the approval's run started), it goes down the order. + +Every other write of the mirror is unchanged, and so is every write on an object that closes on no value of the mirror field. diff --git a/.changeset/37766-approval-closed-states-authoring-rule.md b/.changeset/37766-approval-closed-states-authoring-rule.md new file mode 100644 index 00000000000..a89a93a2bab --- /dev/null +++ b/.changeset/37766-approval-closed-states-authoring-rule.md @@ -0,0 +1,14 @@ +--- +'@objectstack/lint': patch +--- + +feat(lint): an approval that cannot show itself in progress on a field its object closes on is refused where it is authored (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/lint` exports `validateApprovalClosedStates`, `approvalRootObjectsOf`, `APPROVAL_CLOSED_STATE_GAP` and the type `ApprovalClosedStateFinding`; the rule's sentences are registered in all 11 platform locales. + +A new member of the reference-integrity suite, `validateApprovalClosedStates` (finding `approval-closed-state-gap`, at error), judges each flow of a stack as the root of an approval, on each object it can start on a record of, through the one judge the approvals plugin's first request asks (`judgeApprovalOpeningSync`, `@objectstack/metadata-core`). `os validate`, `os build` and `os lint` refuse the gap on a project's stack, and the runtime publish door (Studio, REST `/meta`, MCP) refuses it with `INVALID_METADATA` (422) on a `flow` or an `object` write: an active save, a draft's promotion, a restore and a package publish (a draft save is not refused). An `object` write judges the written package's live flows and is charged only with a gap it adds. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, so a package that declares `closedStates` and repairs its flow in the same publish passes. The rule refuses only what it has in view: a call to a flow the stack does not hold, a node type the spec does not ship and a host with no `job` service are not refused here, and are judged at the approval's first request, which stays the rule. An object that declares no `closedStates` is judged nowhere. + +Why the protocol line reads none: the rule reads only `closedStates`, which this release adds. No object a released version accepts declares it, so nothing that could be published before is refused now. diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md new file mode 100644 index 00000000000..ce7e3b7040f --- /dev/null +++ b/.changeset/37766-opening-check.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): an approval that cannot show itself in progress on a field its object closes on does not open (ADR-0162 Execution item 7, the check) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`, and the input of `ApprovalService.openNodeRequest` gains the optional member `locale` (the run's locale, for the refusal's wording); the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. + +At an approval's first request the plugin now reads the approval whole: the flow its root run was started on and every flow a `subflow` or a `map` in it names, to any depth. Where a step can act on an object that declares `closedStates`: + +- **The between-two-steps set is stamped** on the request, and every later request of the same approval carries the same set. It lists the nodes after which a step of the approval can still follow, so that a run that stops there can later be told from one that stopped after the last step. +- **The approval does not open** where a step mirrors onto a field the object closes on at `pending`, `returned`, `approved` or `rejected`, and one of these is missing: the field declares `pending` and the object closes on neither `pending` nor `returned`; a `state_machine` rule on the field that declares the moves out of a closed `approved` or `rejected` includes `pending` among them; the field has no `readonlyWhen` and no request-status option has a `visibleWhen`; every step that can act on the object mirrors onto the same field; no node that can pause the run (a `wait`, a `screen`, a node type with no descriptor) stands between two steps, and no `map` runs an approval step for items it does not show are not records. An approval one of whose flows cannot be read does not open either, and neither does one on a host that runs no `job` service. + +A refused approval fails its run at the step with `VALIDATION_FAILED` and one sentence per gap naming the flow, the step, the object, the field and what is missing, in the run's locale. No request row is written. + +Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none, once it has been read whole (in an application where some object declares the key, an approval one of whose flows cannot be read is refused, whatever objects the parts that were read act on, since its objects cannot be known); a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. diff --git a/.changeset/37766-opening-judge-metadata-core.md b/.changeset/37766-opening-judge-metadata-core.md new file mode 100644 index 00000000000..545d0778953 --- /dev/null +++ b/.changeset/37766-opening-judge-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the judge of an approval's opening conditions on a closing field lives here, so every door asks one copy (ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `@objectstack/metadata-core` exports the judge the approvals plugin's first-request check used to hold, `judgeApprovalOpening` (it awaits each flow it reads), with `judgeApprovalOpeningSync` (over a stack in hand: a flow read that answers a promise counts as a flow it cannot read), the walk both drive, `approvalFlowWalk`, and the helper and types they read (`closedValuesOf`, `OpeningCheckSource`, `OpeningFlow`, `OpeningFlowBody`, `OpeningGap`, `OpeningJudgement` and the rest). `OpeningCheckSource.calleeFlow` may answer a flow or a promise of one. The verdict and its gaps are unchanged; nothing an author writes changes. diff --git a/.changeset/37766-opening-judge-plugin-approvals.md b/.changeset/37766-opening-judge-plugin-approvals.md new file mode 100644 index 00000000000..1f4f4cfe96b --- /dev/null +++ b/.changeset/37766-opening-judge-plugin-approvals.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +refactor(approvals): the first-request check asks the opening judge in `@objectstack/metadata-core` (ADR-0162 D5) + +Clause-②: no +Metadata-protocol: none + +The check an approval's first request makes on a field its object closes on now calls `judgeApprovalOpening` from `@objectstack/metadata-core`, the same judge the authoring rule `validateApprovalClosedStates` asks. `approval-opening-check.ts` re-exports it and its types under the names it exported before. Which approvals open, the refusal and its sentences are unchanged. diff --git a/.changeset/37766-opening-lead.md b/.changeset/37766-opening-lead.md new file mode 100644 index 00000000000..41fcfa5b582 --- /dev/null +++ b/.changeset/37766-opening-lead.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(approvals): the opening refusal no longer says the object closes on its approval field when its only gaps are the host's or an unreadable flow + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: the plugin's message catalog gains the sentence `approvalOpeningRefusedClosedStatesLead` in all 11 locale packs. + +An approval's first request is refused when an object it can act on declares `closedStates` and the host runs no job service, or when a flow it runs cannot be read. Those gaps are raised whatever field the object closes on. The refusal's lead used to say "the object closes on its approval field" in every case, which is false for an object that closes on another field. Where every gap is one of those two, the lead now says only what is true: the approval can act on an object that declares `closedStates`. The sentences per gap are unchanged. diff --git a/.changeset/37767-hold-root-run-spec.md b/.changeset/37767-hold-root-run-spec.md new file mode 100644 index 00000000000..da86dbe6298 --- /dev/null +++ b/.changeset/37767-hold-root-run-spec.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): a run's writes name the root run of its tree (`ExecutionContext.flowRootRunId`, `HookContext.provenance.flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ExecutionContextSchema` and the `provenance` of `HookContextSchema` gain the optional string `flowRootRunId`, beside `flowRunId`: the run id of the root of the run tree the writing run belongs to (the run itself for a root run). The automation engine stamps it on every write a run makes; it is never read from a request. Nothing an author writes changes. diff --git a/.changeset/37767-hold-root-run.md b/.changeset/37767-hold-root-run.md new file mode 100644 index 00000000000..db64ff6ec72 --- /dev/null +++ b/.changeset/37767-hold-root-run.md @@ -0,0 +1,13 @@ +--- +'@objectstack/core': patch +'@objectstack/objectql': patch +'@objectstack/service-automation': patch +'@objectstack/runtime': patch +--- + +feat(automation): every write of a run carries the root run of its tree (`flowRootRunId`, ADR-0162 D5) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: a data write a run makes (`resolveRunDataContext`, the run identity of `@objectstack/service-automation`) carries `flowRootRunId`, the run id of the root of its run tree, beside `flowRunId`; the engine carries it onto the write's `HookContext.provenance` (`@objectstack/objectql`), the platform system api strips it with the other run marks, a sandboxed body and script see it among the declared provenance members (`@objectstack/runtime`), and it is one of the fields an entry point may not set on an `ExecutionContext` (`assembleExecutionContext`, `@objectstack/core`). The approvals plugin reads it to let every run of an approval through the hold. Absent on a write that is not a run's. diff --git a/.changeset/37767-hold.md b/.changeset/37767-hold.md new file mode 100644 index 00000000000..227e6743eb1 --- /dev/null +++ b/.changeset/37767-hold.md @@ -0,0 +1,23 @@ +--- +'@objectstack/plugin-approvals': minor +--- + +feat(approvals)!: on an object that declares `closedStates`, the document is held for the whole approval (ADR-0162 D5, Execution item 8, the hold) + +Clause-②: yes (narrowing) +Metadata-protocol: semantic +Skills-docs: none — `skills/` names no `closedStates` (git grep, 0 hits); its `lockRecord` rows describe the lock while a request is pending, which this does not change, and `content/docs/automation/approvals.mdx` teaches the hold + +**BREAKING** for a caller that edits a record of an object that declares `closedStates` while its approval is between two steps, or after its last decision until the approval is over: FROM the edit landing (the record was locked only while a request was pending, and only under a node whose `lockRecord` is not `false`) TO the edit refused `409 RECORD_LOCKED`. The same holds for an automation that runs as a user outside the approval's own flow, such as a record-change flow with `runAs: 'user'` that a decision sets off. The one-line fix: make the edit before submitting or after the approval is over, or make it from the approval's own flow, whose every run passes; for such an automation, run it with `runAs: 'system'`. No metadata changes and no stored metadata is refused. + +What the hold is. Every decision on such an approval leaves a mark on its request (`unjudged_since`), cleared once the approval is judged or its next request opens. While a mark stands, the pending lock holds the record and its direct `master_detail` lines as a pending request under a locking node does, whatever field the object closes on and whatever the node's `lockRecord` says. It passes: + +- a system context, the approval status mirror among them; +- a write that carries only the mirror field; +- a write by any run of the approval, the record's run or a `subflow` or `map` run under it at any depth, known by the root run (`flowRootRunId`) the automation engine now carries on every write of a run; a hook's write through its own `ctx.api` carries it, a write a hook makes as another caller does not; +- the revise window of a returned request; +- the record's own delete, which lands and ends the approval: it is marked abandoned on its latest request, its marks are cleared, and nothing is written (the reconciler does the same for a record deleted another way). + +An approval that opened before its object declared `closedStates` left no marks and is not held. The approvals-family lock read (`getRecordLock`, the `/lock` and `/locks` routes) answers for a pending request only, as published: in a passage it answers `{ "locked": false }`. + + diff --git a/.changeset/37767-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md new file mode 100644 index 00000000000..131a7031538 --- /dev/null +++ b/.changeset/37767-outcome-when-approval-over.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): on a field its object closes on, an approval's decision is written when the approval is over (ADR-0162 Execution item 8, the outcome) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only datetime column `unjudged_since` (the mark) and an index on it; the `getRun` member of the automation surface the plugin declares (`ApprovalResumeSurface`) now also types the step log the engine already returns; the plugin's message catalog gains `approvalAbandonedTitle` and `approvalAbandonedBody` in all 11 locale packs, sent on the topic `approval.abandoned`. + +What changes, only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. +- **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. +- **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key, or whose requests could not be placed. An approval on an object that declares the key on another field than the approval's holds nothing back: its decisions are written at once, as before, and the door only clears the mark. diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md new file mode 100644 index 00000000000..8c77832acc2 --- /dev/null +++ b/.changeset/37767-reconciler.md @@ -0,0 +1,29 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds` and `childRunIdsTruncated`, the run's `trigger`, `completedAt` and `summary`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. + +Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further visits of the reconciler after the hour: one each sweep (every 5 minutes by default, the plugin's `escalationScanIntervalMs`), or one each turn of its walk where more requests are marked than one sweep reads. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), a failure between two steps found in a run that ended, and the states the last judgement read that say a run has stopped (`stood`), which the rule for a run that stopped uses, below. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. +- **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. +- **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. +- **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. Only an approval that holds nothing back can wait so: the check at its opening refuses each of the three between two steps of an approval on a field its object closes on. There a placement ends the hold and writes nothing. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first visit past it, and one that was not takes one visit more. A reading that could not be kept leaves on the request the reading kept before it: the next judgement stands on that earlier one, so a state kept earlier can still count, and where none was kept nothing is placed. An approval whose reading is never kept is therefore held with no end. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row, each once two judgements in a row read it so, as above. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. +- **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. +- **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. +- **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. + +- **A refusing end is an end.** The door reads a run that reached an end of the flow as having ended there, a refusing end (`outcome: 'refused'`) included, as it already did for a completed run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key. diff --git a/.changeset/37767-status-mirror-closing-field-refusal.md b/.changeset/37767-status-mirror-closing-field-refusal.md new file mode 100644 index 00000000000..b74af8a9633 --- /dev/null +++ b/.changeset/37767-status-mirror-closing-field-refusal.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +fix(approvals): on a field the object closes on, a refused write of the approval status mirror is no longer swallowed (ADR-0162 Execution item 8) + +Clause-②: no +Metadata-protocol: none + +A validation rule, an option's `visibleWhen` or a hook of the app can refuse the write that mirrors an approval's status onto the record. The mirror used to log every such refusal at `warn` and go on. On a field the object closes on at `approved` or `rejected` (`closedStates`, ADR-0162 D1): + +- **The `pending` of an approval's first request.** The approval does not open. The request's row is voided as `cancelled`, nobody's inbox lists it, no lock is taken, and the run fails at that step with the refusal's own message. The record keeps the value it held, a closed one included. +- **Every other write** (a decision, a send-back, a recall's put-back, a later request's `pending`, the dead-run sweep's put-back). The field keeps the value it held, and the refusal is reported three ways: an `error` line naming the write and the fix, a line with no actor on the request's timeline carrying the refusal's message, and a notice to the organization's administrators under the new topic `approval.status_mirror_refused`, which the notification preference options now list. + +An object that declares no closed state is unchanged: its mirror still logs a refused write at `warn`, and its approval still opens. diff --git a/.changeset/37767-step-child-runs.md b/.changeset/37767-step-child-runs.md new file mode 100644 index 00000000000..fb072d0c442 --- /dev/null +++ b/.changeset/37767-step-child-runs.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(automation): a delegating step records the child runs it started (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `AutomationEngine` gains the public read `runStartedFor(context)` and an optional second argument to `getRun(runId, { strict })`; a node executor's result (`NodeExecutionResult`) gains the optional `childRunIds`, and the exported step type (`StepLogEntry`) gains the optional `childRunIds` and `childRunIdsTruncated`, which the engine writes onto the step's log entry (`ExecutionStepLogSchema`, in `@objectstack/spec`). + +- **`childRunIds` on a step.** A `subflow` step names the one run it started, on every exit: paused on its child, completed, failed or refused. A `map` step names the item runs that execution of the step started. Absent on a step that started none, and on a child that paused with no run id. `getRun` serves it with the rest of the step log, so a reader can walk a run's tree from its root; before this, a parent's link to its child lived only on the parent's pause (`correlation: 'subflow:'`), and only while the parent was parked. +- **A step names at most 200 child runs.** A `map` can start up to 10,000 item runs. A step whose execution started more than 200 names the first 200 started and carries `childRunIdsTruncated: true`, so a reader never takes the list for all of them. +- **What the durable history keeps of the links.** A log of more than 200 steps is compacted for history: it keeps every top-level step and every failure while those number 200 or fewer, and otherwise the most recent 200 of them, so compaction can drop a step with its link. A terminal run's step log over the history row's 64 KB cap is stored without every step's `childRunIds`, each step that named child runs marked `childRunIdsTruncated: true`, before any step is dropped; only a log still over the cap without them is halved from its head, as before. A mark costs 28 bytes on each step it lands on, so a log that fits the cap without its links by less than its marks' bytes is halved where a log that never named a child run was not. +- **`runStartedFor(context)`.** A run that ends inside `execute` answers no `runId` (the contract sets it on a paused run only). The engine now answers the id of the run the last `execute` call started for that very context object, whatever it ended in. A run is named once it is past the gates that skip it and leaves a history row, or where it fails before its first node and is recorded as failed; `undefined` where no run started (the flow was missing, disabled, had no start node, or its start condition or the re-entry guard skipped it). Under `errorHandling.strategy: 'retry'` it is the last attempt that started a run. The `subflow` and `map` nodes read it for a child that ended inside the call. +- **`getRun(runId, { strict: true })`.** A store that fails is still logged and read as `null` by default. With `strict`, its failure is thrown instead, so a caller that decides on a missing run can tell a run with no row from a store that did not answer. + +Unchanged: what a run does, the `runId` the contract returns, every existing step field, and which steps a run's history row keeps, but for the marks' bytes above. diff --git a/.changeset/37767-step-log-child-runs-spec.md b/.changeset/37767-step-log-child-runs-spec.md new file mode 100644 index 00000000000..1ed247148c4 --- /dev/null +++ b/.changeset/37767-step-log-child-runs-spec.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): a run's step log names the child runs a step started (`ExecutionStepLogSchema.childRunIds`, `childRunIdsTruncated`, ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — `skills/` names none of `ExecutionStepLog`, `childRunIds`, `childRunIdsTruncated` or `runStartedFor` (git grep, 0 hits): the step log is a runtime record no skill teaches an author to write + +Widened: `ExecutionStepLogSchema` gains two optional keys. `childRunIds: string[]`: the run ids of the child runs the step started, the one run of a `subflow` and, for a `map`, the item runs that execution of the step started, at most 200, the first ones started. Absent for a step that started none. `childRunIdsTruncated: true`: the step started more child runs than `childRunIds` names, either more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. The engine writes both (`@objectstack/service-automation`); a reader of `getRun` can walk a run's tree from its root with them. Nothing an author writes in a flow changes. diff --git a/.changeset/37768-closed-state-refusal-sentences.md b/.changeset/37768-closed-state-refusal-sentences.md new file mode 100644 index 00000000000..7cd9079c9bb --- /dev/null +++ b/.changeset/37768-closed-state-refusal-sentences.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/service-storage': patch +--- + +feat(spec,objectql): the closed-state refusal's own sentences, in every locale (ADR-0162 D8) + +Clause-②: yes (widening: new keys in the published Operation Message Catalog and the upload-link copy; contract-review-tier review owed) +Metadata-protocol: none + +A write refused because a record is in a closed state (`409 RECORD_LOCKED`, ADR-0162) tells the person what happened, in their own language, with a sentence from the Operation Message Catalog. + +- **New catalog keys** in `BUILTIN_OPERATION_MESSAGES`, in every locale the catalog carries (en, zh-CN, ja-JP, es-ES), overridable per deployment under `errors.` like every other key: `record_closed` with its `_unlabeled`, `_untitled` and `_opaque` forms, and `record_closed_delete_blocked` with its `_untitled` and `_opaque` forms. English, for example: "Invoice 'Northwind March' is closed, so it and its lines can no longer be changed or deleted", and "Customer 'Contoso Holdings' cannot be deleted: deleting it would also remove a closed Invoice or one of its lines". +- **The engine words the refusal from them.** The refusal names a title only from a field that holds display text and that the writer's generic read returns, and that the writer is served under its own field permissions (readable and queryable): not a field the generic read withholds (`internal`, or a credential type), not a reference field, not a field the object's `closedStates` names. Otherwise the sentence names the object's label only, and so it does when a registered security service cannot be resolved. With no security service registered there is no field-level security, and the title is named. A line's write names its master by label alone. A delete refused for what it would also remove names the record asked to be deleted and the label of the object in the way, with the title only when the delete names exactly one record by id. No sentence carries a record id, an API name or a state value. +- **On the error**: `userMessage` and the wire's `error` carry the sentence; `message` reads `RECORD_LOCKED: ` followed by the sentence, as the approval lock's refusal does; the developer sentence moves to `developerMessage`, which the REST layer does not relay. A refusal that could not judge the write keeps the developer sentence and sets no `userMessage`. +- **Upload-link page**: a closed-state refusal reaches the page with the engine's declared catalog sentence, which the page shows. The page's own `recordLocked` answers only a `RECORD_LOCKED` with no declared sentence. The page also carries a closed-state sentence (`recordClosed`) in each of its 11 languages; choosing it by the lock's reason comes with a later change. diff --git a/.changeset/37768-closed-states-metadata-core.md b/.changeset/37768-closed-states-metadata-core.md new file mode 100644 index 00000000000..708da5d7204 --- /dev/null +++ b/.changeset/37768-closed-states-metadata-core.md @@ -0,0 +1,10 @@ +--- +'@objectstack/metadata-core': patch +--- + +feat(metadata-core): the field-level-security scrub serves an object's closed states without the fields a caller cannot read + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +`closedStates` (ADR-0162 D1) is classified in the object-schema FLS reference table as a map keyed by this object's fields: an entry whose field is denied to the caller is left out of the served definition, and a map left empty is deleted. The listed values are option codes, never field references, so a value spelled like a denied field is served as written. The stored declaration is untouched. diff --git a/.changeset/37768-closed-states-objectql.md b/.changeset/37768-closed-states-objectql.md new file mode 100644 index 00000000000..8042146d6ff --- /dev/null +++ b/.changeset/37768-closed-states-objectql.md @@ -0,0 +1,17 @@ +--- +'@objectstack/objectql': minor +--- + +feat(objectql): a record in a closed state, and its lines, are closed to change (`closedStates`, ADR-0162 D2 to D7, D10) + +Clause-②: yes (widening: the engine enforces the new optional key `ObjectSchema.closedStates`; an object without it behaves exactly as before) +Metadata-protocol: none + +A record whose stored state is one of the values its object lists in `closedStates` is closed, and so are its direct `master_detail` lines (a junction row is a line of both masters). Every write a system context does not make is refused `409 RECORD_LOCKED`, with `reason` (`record_closed`, `master_closed`, `cascade_reaches_closed`, `cannot_judge`), `object`, `blockingObject` and `lockReason: 'closed_state'`; the message names no record id and no state value. + +- **What is judged**: an update or delete of a closed record; a line create, update, delete or move under a closed master, or out of one. An update is judged by the stored row, not by its payload, so the write that closes a record lands whole, other fields included, and the next write is refused. A write with no context is bound. +- **Many-row writes are refused whole**, before any row is written: one existence probe where the store compiles the line semi-join (SQL, the memory driver), otherwise the write's one read of its matched rows, under the engine's per-row ceiling. +- **Refused when it cannot be judged**: a master named in a form the engine cannot read as one id, a master or state read that fails, a many-row line write over the ceiling on a store with no probe. +- **Cascades and restore**: a delete whose cascade reaches a closed record removes no row, with or without transactions; restoring a line under a live closed master that is not part of the entry is refused. The referential clear of a deleted record's references, the recycle-bin relink, and the roll-up summary recompute (a system context) land. Change Owner and the hand-over of a banned user's work are bound like any edit: each closed record is listed among the failures. +- **Placement**: after the permission and record-access gates, before the before-hooks; a master the write names is checked through the caller's own read first. A master a before-hook supplies is not judged. +- **The registry fold** keeps a package's declaration honest: an extension's redeclaration that removes, retypes, makes multi-value or narrows a field the declaration names is refused (the field stands, and the fold logs it once), and a tenant overlay may add closed values but may not shorten the package's list or break a field it names. diff --git a/.changeset/37768-closed-states-platform-objects.md b/.changeset/37768-closed-states-platform-objects.md new file mode 100644 index 00000000000..b57babeb0eb --- /dev/null +++ b/.changeset/37768-closed-states-platform-objects.md @@ -0,0 +1,10 @@ +--- +'@objectstack/platform-objects': patch +--- + +feat(platform-objects): the Studio object form's closed-states row is translated in every metadata-forms locale pack + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +The object form's Advanced section offers `closedStates` (ADR-0162 D1); its label and help text are authored in all eleven metadata-forms locale packs. diff --git a/.changeset/37768-closed-states-spec.md b/.changeset/37768-closed-states-spec.md new file mode 100644 index 00000000000..4a410432ed6 --- /dev/null +++ b/.changeset/37768-closed-states-spec.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): an object declares its closed states (`closedStates`, ADR-0162 D1) + +Clause-②: yes (widening: one new optional authorable key, `ObjectSchema.closedStates`) +Metadata-protocol: added + +An object may now declare the states in which its records are closed: a map from a stored, single-value `select` field of the object to the list of that field's option values that close a record, e.g. `closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when any listed field holds one of its listed values. In a closed state the record and its direct `master_detail` lines are closed to change for every caller that is not a system context. + +- **Refused where the object is authored**, at parse and at the metadata save and publish door, one located issue each: a key that names no field of the object; a field that is not a single-value `select` (another type, `radio` included, or `multiple: true`); a select whose options are not declared inline on it (a `picklist`-backed select); an empty list; a value that is not one of the field's options; a value listed twice. So is the edit that would leave such a declaration behind: removing or retyping a field, or removing an option, that a declaration still names. Take the entry out of `closedStates` first. +- **Optional**: an object without the key behaves exactly as before. A line object declares nothing to be closed with its master, and may declare its own `closedStates`. The key has no tie to a `state_machine` rule in either direction. +- Liveness row `object.closedStates`, the Studio object form's Advanced section offers it as a JSON row, and the reference docs, authorable-surface record and state counts are regenerated. +- The error-code ledger registers `RECORD_LOCKED` for `@objectstack/objectql`, the engine's closed-state refusal, beside the approval lock that already emits it. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 9adaf844c92..6c5742c1ef4 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -408,6 +408,10 @@ never deadlock against itself. The exemption is keyed on run identity rather tha elevation, so a `runAs:'user'` run stays row-level-security scoped while it writes — it does not become a system write. +On an object that declares `closedStates`, the document is held for the whole +approval, between its steps as well, and every run of the approval writes it: +see [the hold](#hold). + **The record's lines are locked with it.** Rows of a `master_detail` child of the locked record (an expense claim's lines, an opportunity's products) refuse insert, update and delete with the same `409 RECORD_LOCKED`, and so does moving a row into @@ -1410,6 +1414,424 @@ in-flight request, `reassign` hands one slot to another user directly. - Forget rejection paths - Hard-code approvers +## Approvals on an object that declares `closedStates` [#closed-states] + +An object can declare [`closedStates`](/docs/references/data/object) (ADR-0162): +values of its own `select` fields on which a record and its direct +`master_detail` lines are closed to every caller that is not a system context, +who is refused `409 RECORD_LOCKED`. The approval status mirror writes in a system +context, so it can move such a record: the `pending` of a new approval takes a +document off a closed `approved`. That is why the platform asks more of an +approval on such an object, and what this section describes. In an application +where no object declares `closedStates`, none of it applies and nothing is read. + +### Which approvals are judged, and when + +An approval here is one passage of a record through its approval flow, taken +whole: the run started for the record and every child run under it, a `subflow` +body or an item of a `map`, to any depth. It holds one request for each step it +reaches, and one more each time a returned request is resubmitted. ADR-0044 +numbers those resubmissions as the rounds of a request, and the word means +nothing else on this page. + +The platform judges an approval once, at its first request, before anything is +written. It reads every approval step of the flow the record's run was started +on and of every flow a `subflow` or a `map` in it names, to any depth, each with +its own `approvalStatusField` and every object it can act on: the record's +object, and under a `map` the object the node names for its items as well. A +later request of the same approval is not judged again, since refusing it would +end the approval between two steps that were already decided. Nor is a request +the platform cannot place as first or later, which is a request of an approval +whose earlier requests were opened before requests recorded the run they +belong to. So an approval that was in flight when its object first declared +`closedStates` is not held to what follows. + +A step is **concerned** where the object closes on its mirror field at a status +the mirror writes for a request that is not abandoned: `pending`, `returned`, +`approved` or `rejected`. An object that closes on that field only on values of +its own, such as `paid` or `void`, is asked none of the field and flow +conditions below. + +### What the mirror field owes + +For every concerned step, the step's mirror field: + +- **declares `pending`**, and the object closes on **neither `pending` nor + `returned`**. Those are the statuses of a request in flight, and the revise + window of a returned request opens on `returned` (ADR-0044). +- has **`pending` among the moves out of a closed `approved` or `rejected`**, + wherever a `state_machine` rule on the field declares those moves. A new + approval of a decided document opens it by writing `pending`. +- carries **no `readonlyWhen`**, and **no `visibleWhen` on its options for a + request's status** (`pending`, `returned`, `approved`, `rejected`, + `recalled`). The platform does not evaluate those predicates ahead, and on a + record where one holds it takes away a write the mirror needs. Keep callers + off a mirror field with `readonly`, which the mirror passes. + +The field's other rules and hooks cannot be read ahead, and they meet every +write of the mirror. A `state_machine` rule on the field owes the mirror its +other moves as well: from `pending` to each outcome, and out of `pending` and +`returned` when a request is abandoned. Where the object closes on the field at +`approved` or `rejected`, a write of the mirror that a rule or a hook refuses is +not swallowed: + +- **The `pending` of an approval's first request.** The approval does not open. + The request just written is voided as `cancelled`, its timeline carries the + refusal, no lock is taken, and the run fails at that step with the refusal's + own message. The record keeps the value it held. +- **Any other write.** The field keeps the value it holds, and the refusal is + reported three ways: an `error` line in the server log, a line with no actor on + the request's timeline that carries the refusal's message, and a notice to the + organization's administrators, who can change the rule. + +### What the flow owes + +- **One mirror field for every step.** Every approval step that can act on a + record of the object names the same mirror field as the concerned step. A + step that names another field, or none, refuses the approval, whether it comes + ahead of the concerned step or after it. A step in a `map` body counts as one + that can act on the parent's record, unless the node writes its items out and + every one of them is a record. +- **No pause between two steps.** *Between two steps* means after a step is + decided, either way, and before the next step opens. The next step can be the + same step opened again, so in a `map` or a `loop` body that holds a step, a + node after the body's last step stands between two steps too. No node that can + pause the run of itself may stand there, in a flow that runs as the user or in + one that runs as system: a `wait` or a `screen` there would hold the document + in approval with nobody asked to decide. The platform reads this off the node + type's descriptor (`supportsPause`), and reads a `subflow` or a `map` through + the body it calls. The revise window of a returned request (`approval_revise`) + is not such a pause. +- **A node type without a descriptor.** A node whose type publishes no + descriptor counts as one that can pause, and so does a node whose type the + platform cannot read: such a node between two approval steps refuses the + approval. The structural types `start` and `end` have no executor and never + pause, so the `end` of a `map` body or of a `subflow` body refuses nothing. +- **No `map` of approvals on the parent's record.** Where a concerned step can + act on the parent's record, the approval holds no `map` with an approval step + in its body, at any depth, unless the node writes its items out and none of + them is a record. An item that is a record has its request filed on the item, + and the parent's run waits on it as it would on a pause. A parent run that + carries no record, such as a batch sign-off that hands a `map` its items, is + not refused on this ground. +- **Readable whole.** Every flow a `subflow` or a `map` names is one the + platform can read. An approval it cannot read whole cannot be judged, and is + refused. + +One more ground is the host's, not the author's. An approval any step of which +can act on an object that declares `closedStates`, concerned or not, opens only +on a host that runs the approvals plugin's sweeps, which needs a `job` service. +The sweeps are what release a record held by a dead run, and what judge an +approval that no action judged, below. + +### An approval that does not mirror onto the closing field + +An approval none of whose steps mirrors onto a field the object closes on is +asked none of the field and flow conditions, only the host's. It moves nothing on +the closing field, so it does not open a closed document: a record that is closed +stays closed through it, on the value its last writer left, and every caller's +edit of it is refused, in the revise window after a send-back as well. Such an +approval is not a way out of the closed state. Where a closed document should +not be sent for approval at all, gate the flow's start on the state. + +### Each item under a `map` is an approval of its own record + +Under a `map` whose items are records, each item's request is filed on that +item, on the object the node names for its items, and what follows is judged for +that record alone: + +- the item object's closed values and mirror field are judged, with the rest of + the approval, at the approval's first request; +- the submitter is told an item's outcome without waiting for the items after it; +- when an item's request is abandoned, only the requests on that item's record + count, never another item's (below). + +### What a refused opening is for the person who submitted + +When the check refuses, the approval does not open: no request is written, +nothing is mirrored, no lock is taken, and nobody is asked to decide. The +approval node fails the run with a `VALIDATION_FAILED` error, and that failed run +is what the person who submitted sees. Its message names the record whose +approval was not started, and then, for each gap, the flow, the step, the object, +the field and what is missing. Its lead says that the object closes on its +approval field only where a gap concerns that field; where the only gaps are the +host's or a flow that could not be read, the lead says instead that the approval +can act on an object that declares `closedStates`. The message is in the run's +locale where the plugin carries it, and in English otherwise. The record keeps the +value it held, and the server log carries a warning that names the gaps. + +Nothing in the message is the submitter's to fix: every gap is the app's +configuration or the host's. Whoever maintains the app fixes the field, the flow +or the host, and the submitter then submits again. + +### Refused where the approval is authored + +The same conditions are refused before anyone submits, wherever the flow and +the object are in view together. `os validate`, `os build` and `os lint` fail +on a project's stack with the finding `approval-closed-state-gap`, one per gap, +in the same words as the refused opening. Studio, the REST `/meta` API and MCP +refuse to save or publish a `flow` or an `object` that would leave a gap, with +`INVALID_METADATA` (422) and the same words: at an active save, when a draft is +promoted, at a restore, and in a package publish. A draft save is not refused; +its promotion is. A package that declares `closedStates` and fixes its flow in +the same publish passes. + +An authoring door judges only what it has in view, so the refusal at the first +request stays the rule. These are left to the first request: + +- a flow that a `subflow` or a `map` names and the project or the deployment + does not hold there. When one flow is saved on its own, the flows it calls and + the flows that call it are not in view; +- a node type that a plugin adds, between two steps. At authoring only the + spec's own pausing types, such as `wait` and `screen`, count as a pause; +- whether the host runs a `job` service; +- a flow that declares no object, with no `start` object and no record input, + started by an action or by name on a record. At authoring a flow is judged on + its `start` object, or where it declares none, on the object of each record + input; the first request judges on the record the run was started on. + +### What an abandoned approval leaves + +Three writers abandon a request: its submitter's recall, of a pending request or +of a returned one in its revise window; an administrator's override of a pending +request, the override arm of the same recall; and the sweep that releases a +record held by a dead run. Each records `recalled` on the request. The platform +also abandons an approval whose run ended between two steps, below, at the +action that found it or in the reconciler: the requests keep the decisions +already made, a line with no actor on the latest request's timeline says that +the approval did not go on, why, and what the record was put back to, and the +submitter is told, and submits again. Where the object closes on the mirror +field at any value, one of its own or a status, an abandoned request never +writes a closed value of that field: + +1. **A closed value the approval did not write is left alone.** Where the field + holds a closed value that no request of this approval on this record had as + its status, another writer put it there, and the mirror writes nothing. A + request of the same approval on another record, another item of a `map`, does + not count. +2. **Otherwise `recalled`**, where the field declares it, or declares no options, + and the object does not close on it. +3. **Otherwise the first usable value in this order:** the value the field held + at submit, the field's declared default, empty. A closed value is passed over + at each step, and so is a value the field does not declare. On a required + field an empty value at submit is passed over for the default. + +So listing `recalled` among the field's closed values closes nothing through the +mirror: a withdrawn approval leaves the record open. A record that was closed +when it was submitted, and that the approval opened, is left open on the value a +never-submitted record carries, its default or empty. To close a withdrawn +document, use an action or a flow of the app's own. To show a withdrawn approval +on the record, declare `recalled` among the field's options and do not close on +it. + +Where the platform cannot tell whether the approval wrote the closed value the +field holds, because the abandoned request, or one opened on the record since the +approval's run started, does not record the run it belongs to, it goes down the +order. The server log says when the mirror withholds a declared `recalled` (a +warning) and when it passes over a closed value or leaves one alone. On a +required field that is not `readonly`, with no default the mirror can use, the +write of empty is refused: the field keeps the value it holds, and the refusal is +logged, and reported as above where the object closes on the field at `approved` +or `rejected`. + +### When the outcome lands on the record + +Where the object closes on a step's mirror field at `approved` or `rejected`, +the step's decision is held back: the request records it, and the field keeps +`pending` until the approval is over for the record. Every other status is +written as before: `pending` as a request opens, `returned` at a send-back, and +what an abandoned request leaves. + +So a node that follows a decision in the flow reads `pending` on the field, not +the decision, and a flow or a trigger that fires when the field becomes +`approved` fires once, when the approval is over, not at each step. A node that +needs a step's decision reads it on the step's outcome, as the flow's own edges +do. + +After each action that moves a run of the approval on (a decision, by a person +or by the escalation clock, a send-back, a resubmission, a recall, and the +continuation of a restored run), the platform reads the approval's requests on +the record and every run of the approval: the run that carries the record and, +through the steps that started them, every `subflow` child under it, and every +`map` item run that does not carry another record (an item that is a record has +an approval of its own). It answers one of: + +- **In progress.** A request is pending or returned on the record, or a run is + parked at a node between two steps. A run parked there on a child run counts + as what its child run is. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, to an end or to a pause no step follows, or a later step + could not open, and no request of the approval opened after it. The approval + is abandoned, above. +- **Cannot tell.** A run is being advanced by another process, the store did + not answer for a run, or the requests cannot be read. Nothing is written. +- **Finished**, otherwise: every run reached an end of the flow, a refusing end + included, stopped after the last step, or is parked at a pause no step can + follow. The latest request's decision is written, in the name of the person + who decided it. + +The platform keeps what it read on the approval's own requests, at each of these +actions, one that leaves the next request pending included, and as each request +opens: the runs it read to their end, and a failure between two steps it found +in one. A run is not read again once it, and every run its steps started, were +read to their end. Until then it is read again at the next action or sweep, so +a run that a stored step lists, and that the platform could not read once, is +not passed over later. One reading takes at most 200 runs beside those it does +not read again; a larger tree cannot tell on that reading and is read on at the +next. That has an end: once the approval's marks have stood for an hour, the +platform reads on only while a reading adds to the runs it does not read again +(it keeps at most 200 of them), and the reading that adds none places the +approval by the step last decided, below. Two costs come with that. An approval +whose runs the platform cannot finish reading is placed without having been +read to its end, and that can begin at about 399 runs: for a `map` step of 199 +items that each call a `subflow`, every reading takes the run and its 199 item +runs, and never the runs below them. And the cause is the shape of the flow, so +the same approval submitted again can meet the same end: give one approval +fewer runs to read, because submitting again does not help. Reading on can take +up to 200 further visits after the hour. The reconciler visits an approval once +a sweep, every five minutes by default (the plugin's `escalationScanIntervalMs`), +or once a turn of its walk where more requests are marked than one sweep reads, +below. + +The platform trims every flow's run history in time. A run it read before that +is not needed again. A run it never read counts as passed where the history of +a run it did read shows that the flow went on past the step that started it: +that step succeeded, and the flow reached an end or went on to a later step. +Such a run does not hold the approval. A step that failed does not count, also +where the flow routed the failure and went on. + +Four more states cannot tell at first: a run with no history left to read, +which the platform never read and which no run it read went on past (a process +stopped while it was advancing it); a run whose history does not list every run +its steps started (a `map` step that started more than 200 item runs, or a step +history that lost steps, or the lists of the runs its steps started, to its +size limit when it was stored); an approval with more runs than the platform +can read in full, above; +and a decided request whose run is still parked at that request's own step (a +process stopped before the run was resumed), in the run that carries the record +or in a `subflow` or `map` run below it. An hour after the approval's marks +were set, each has stopped at the step last decided, once two checks in a row +find it in the same state. The hour is counted from the marks, not from when +the run last moved, and a run the platform is resuming at that moment looks +like one a stopped process left: a run with no history to read, or a paused run +with nothing to resume it. An approval can wait longer than an hour between two +steps by design (a `wait` node, a batch of records approved one by one) only +where none of its steps is concerned: the flow conditions above refuse both for +one that is. Such an approval holds nothing back, and it is past the hour +whenever it resumes. So the check that first finds a run in such a state only +notes it, and the next check places the run if it finds the same. A check made +within the hour counts as the first, so this adds one visit of the reconciler, +and only where the check before did not find the same: one sweep, five minutes +at the default interval, or one turn of the walk where more requests are marked +than one sweep reads. Where a later step could +follow that step, the approval is abandoned, above, and a run still parked +there is cancelled, with the runs that wait on it, so nothing resumes it; the +decisions already made stay on their requests, and the submitter submits again. +The cancel is not tried again once the record is put back: where it fails, the +run stays parked, the approval stays abandoned, and continuing that run is +refused. Where the step was the last, its decision is written and, once it is +on the record, the organization's +administrators are told that the flow could not be seen through to its end +after that step (the notice `approval.flow_not_continued`). The run's pause is left: where the run is still +paused, an operator can continue the flow's remaining nodes or cancel the run; +where it has ended or no run is left, check that the steps after the decision +were done. A write that a rule or a hook refuses sends no such notice; the +notice goes out with the write that lands. An approval placed for a history +that does not list every run, or for more runs than the platform can read, can +be one whose flow did go on: the platform could not read it in full, so the +notice asks for a check and does not state a failure. + +A step history that loses whole steps carries no mark of it; this is a limit +of this release (ruling 7268216330 on #37767). The platform marks one thing: a +step that lost the list of the runs it started. Whole steps are lost in three +ways: a run that logged more than 200 steps is stored with 200 of them (its +top-level steps and its failed steps first, then the most recent of the rest); +a history over its 64 KB limit is stored as its most recent steps; and one that +still does not fit is stored with none. The platform reads what the history +kept, and a run named only by a step that was dropped reads as one the flow +went past: it is not read. In the last two cases the platform can still tell, +from the run's count of its steps, that steps are missing, and treats the +history as one that does not list every run, above. In the first it cannot. A +`subflow` or `map` step that is not among the 200 (one that succeeded inside a +`loop`, `parallel` or `try_catch`, or an early step of a very long run) no +longer lists the runs it started: a failure the flow routed inside one of them +is not seen, and the approval can be written as finished, with no notice. A +process that still holds the run in memory reads all of its steps. For a flow +whose run can log more than 200 steps and that starts child flows inside such a +region, read the outcome of those child runs in the flow's run history as well. + +Every decision on an approval any step of which can act on an object that +declares `closedStates` leaves a mark on its request (`unjudged_since`), also +where nothing is held back. The mark is cleared once the approval is judged, or +when its next request opens. The plugin's sweeps run a reconciler that judges +every approval whose mark still stands, as the action would have: after a run +that was cancelled, a parent run cancelled while its child's request was pending, +or a process that stopped, as above. Each sweep reads the oldest marks and the +next page of a walk over every marked request, so that approvals that stay in +progress do not keep the newer ones from being judged. Once the mark has stood +for an hour, it also reads as stopped where it stood a run that reports paused +while its pause is gone, and a run parked at a `subflow` or a `map` whose child +run has ended or has no history left, each once two sweeps in a row find it +so. That holds for a `map` over records too: +the platform does not read such an item run's steps, which belong to the item's +own approval, only whether the run has ended. +Where nothing was held back it clears the mark and writes nothing; where it +concluded that a run had stopped, a line in the server log says so. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the approval is over: +it is marked abandoned on its latest request, its marks are cleared, and nothing +is written. The delete does that as it lands, below, and the reconciler does it +for a record that went another way. + +### The document is held for the whole approval [#hold] + +On an object that declares `closedStates`, every approval holds the document from +its submission until it is over: while a request is pending, as on any object, +and also through each passage, from a step's decision until the next request +opens or the approval is over (ADR-0162 D5). A passage holds the record and its +direct `master_detail` lines as a pending request does, whatever field the +object closes on and whatever the step's `lockRecord` says: a step that leaves +the record open while its request is pending (`lockRecord: false`) still holds +it once that request is decided. A caller's edit in a passage is refused +`409 RECORD_LOCKED`, so the document cannot change between the decision on it +and the outcome the approval writes. That caller includes an automation that +runs as a user outside the approval's own flow: a record-change flow with +`runAs: 'user'` that a decision sets off starts a run tree of its own, and its +write to the document is refused the same way. Run such a flow with +`runAs: 'system'`, or make the write from the approval's own flow. + +What passes the hold: + +- **The approval's own runs.** A write made by any run of the approval, the run + started for the record or a `subflow` or `map` run under it at any depth, a + hook's write through its own `ctx.api` included, lands. A run is known by the + root run it belongs to, which the automation engine carries on every write of + a run (`flowRootRunId`, beside `flowRunId`). A write a hook makes outside that + context, as another caller, is refused. +- **A system context**, the approval status mirror among them. +- **A write that carries only the mirror field.** +- **The revise window** of a returned request, as on any object. +- **The record's own delete.** It lands and ends the approval: the approval is + marked abandoned on its latest request, its marks are cleared, and nothing is + written. A line's delete, or a delete that cascades into a line, is held as + an edit is. + +A passage lasts as long as the approval's marks stand (`unjudged_since`, above). +A run that pauses between two steps, at a `wait` or a screen, holds the +document while it waits; so does a process that stops in a passage, until the +reconciler judges the approval: at its next sweep where the runs can be read, +otherwise once the hour above has passed. Where that is too long for the +business, the flow should not pause between two steps on such an object. + +An approval that was in flight when its object first declared `closedStates` +left no marks, and is not held between its steps. + +The approvals-family lock read (`getRecordLock`, above) answers for a pending +request only: in a passage it answers `{ "locked": false }` while an edit is +refused `409 RECORD_LOCKED`. A page that offers an edit in a passage learns of +the hold from the refusal. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. @@ -1427,6 +1849,6 @@ Separating *who configures* from *who approves* from *as whom it runs* is the sa ## See also -- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization). +- Decision records: **ADR-0049** (`runAs`), **ADR-0066** (unified authorization), **ADR-0044** (send-back and resubmission), **ADR-0162** (closed states and the approvals on them). - Guide: [Hooks](/docs/automation/hooks) and [Flows](/docs/automation/flows); [Who can see data / automation / interface](/docs/permissions/access-recipes). - Reference: [Flow](/docs/references/automation/flow), [Approval](/docs/references/automation/approval). diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index fdade0ae738..f81d7258820 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -117,6 +117,7 @@ A hook body sees the same server-stamped write provenance an in-process handler | Member | Present when | |---|---| | `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. | +| `ctx.provenance.flowRootRunId` | Set beside `flowRunId`: the id of the root run of that run's tree, the run itself for a run no other run started. Absent on a run the engine could not place in a tree. | | `ctx.provenance.attributedUserId` | The write is authorized as the system and credited to a real person (for example, the admin behind an identity-adapter call). | | `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. | | `ctx.provenance.performedByAgentId` | The in-product AI agent performed the write for the signed-in person in `ctx.session.userId`, whose write it runs as; the value is the agent's name. | diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index ff29fd9e7cd..9522c1f49cd 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -159,6 +159,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 29e | A restore of an entry someone else deleted asks **no recycle-bin grant** | objectql | Get: the system restores any entry. Every caller that is not system restores only the entries whose `deleted_by` is its own `userId` unless its effective permissions grant `manageRecycleBin` on the entry's object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerMayRestoreEntry` | | 29f | Listing the recycle bin of an object asks **no recycle-bin grant** | objectql | Get: the system lists every entry of any object the bin takes. Every caller that is not system lists an object's entries only when its effective permissions grant `manageRecycleBin` on the object; otherwise `403 PERMISSION_DENIED`, and the same refusal when no permission resolver is registered or it throws (#30237, ADR-0148 D5) | `assertCallerManagesRecycleBin` | | 29g | A validation rule message's `{{ }}` holes show **every field the system may read**, only when the write names no person | objectql | Get: a user-less system write (a schedule, a platform sweep) fills a refused write's message holes with the security service's system answer, every field less credential and `internal` ones; that sentence reaches the server log alone. An elevated write that names a person (`userId`: a `runAs: 'system'` flow they started, whose refusal reaches them as `innerRefusal`; an action body; the approvals mirror) is not read as the system: both field projections are asked for that person, with the permission sets the context carries or their own grants (`resolveUserAuthzGrants`), and every hole renders empty when those grants cannot be read (#37909) | `readerContext` | +| 29h | **The closed-state lock does not bind** — a write to a record in one of its object's `closedStates`, or to a line of one, is not judged | objectql | Get: a system context updates, deletes and restores a closed record and its `master_detail` lines, and a cascade that reaches one runs; the engine's own derived writes (the roll-up recompute, the approval status mirror) land on a closed record. Every caller that is not system, and a write with no context at all, is refused `409 RECORD_LOCKED` (ADR-0162 D5) | `boundByClosedStates` | | 30 | **Bulk data event `organizationId` OMITTED** — the batch is published "not asserted" | plugin-security | Get: nothing — the `data.records.*` event still publishes. Lose: the per-organization attribution: this exit is taken before the security middleware composes any tenant wall, so it records no Layer 0 verdict on the operation (`OperationContext.tenantLayer0Verdict`, #15813), and the engine's bulk producer — which reads that recorded verdict and nothing else — omits the key rather than filling it from the caller's `tenantId`; a tenant-scoped consumer then does not deliver the event inside an organization wall (#15225) | `registerAuthzMiddleware` | | 30b | **The import doors admit a control opt-out** — `runAutomations: false` and `treatAsHistorical: true` on `POST /data/:object/import` and `/import/jobs` | rest | Get: an import whose rows are written with `skipAutomations` (no metadata-bound hook, no record-change trigger: an app's approvals and record freezes among them) or with `skipStateMachine` and `preserveAudit`. Every other caller, every signed-in user and administrator included, is refused `403 PERMISSION_DENIED` before the body is parsed, so nothing is written and no job is created. Inbound HTTP never carries the flag, so this is an in-process caller's door. Note: the flag still suppresses none of those controls by itself (see below); it only admits the opt-outs that do | `importControlOptOutRefusal` | | 30c | **The import undo keeps the control skips** — `POST /data/import/jobs/:jobId/undo` | rest | Get: an undo whose deletes and restores are written with `skipAutomations` and `skipStateMachine`, so no metadata-bound hook, record-change trigger or `state_machine` rule refuses a reversal. Every other caller, every signed-in user and administrator included, undoes under those controls: a reversal one of them refuses is reported per row in the undo answer's `failures` and kept in the job's undo log, and the job is stamped reverted only once every row is. A historical job's `preserveAudit` belongs to the job, not the caller, and rides every undo. Inbound HTTP never carries the flag, so this is an in-process caller's door | `importUndoWriteContext` | @@ -551,6 +552,7 @@ and CI refuses one that differs from what the tree produces. | `packages/metadata-core/src/meta-write-capability.ts#metaWriteCapabilityVerdict` | 1 | 51 | | `packages/metadata-core/src/meta-write-capability.ts#walledCatalogWriteVerdict` | 1 | 55b | | `packages/metadata-core/src/object-schema-fls.ts#isObjectSchemaMaskExempt` | 1 | 8 | +| `packages/objectql/src/closed-state-lock.ts#boundByClosedStates` | 1 | 29h | | `packages/objectql/src/credential-evaluation-guard.ts#rejectCredentialEvaluation` | 1 | 18c | | `packages/objectql/src/engine-cascade-planning.ts#dependentCountIsDisclosable` | 1 | 28 | | `packages/objectql/src/engine-delete-cascade.ts#recordReferenceCheckElevation` | 1 | 29 | diff --git a/content/docs/references/automation/execution.mdx b/content/docs/references/automation/execution.mdx index 610c160b022..8f402a0cbf2 100644 --- a/content/docs/references/automation/execution.mdx +++ b/content/docs/references/automation/execution.mdx @@ -150,6 +150,8 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionLog.summary` @@ -210,6 +212,8 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionStepLog.error` diff --git a/content/docs/references/data/data-engine.mdx b/content/docs/references/data/data-engine.mdx index 7b603eab15c..00a619378bb 100644 --- a/content/docs/references/data/data-engine.mdx +++ b/content/docs/references/data/data-engine.mdx @@ -70,6 +70,7 @@ const result = BaseEngineOptionsSchema.parse(data); | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -128,6 +129,7 @@ Options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -184,6 +186,7 @@ Options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -241,6 +244,7 @@ Options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -320,6 +324,7 @@ Options for DataEngine.insert operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -382,6 +387,7 @@ Query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -470,6 +476,7 @@ Options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -547,6 +554,7 @@ QueryAST-aligned options for DataEngine.aggregate operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -636,6 +644,7 @@ QueryAST-aligned options for DataEngine.count operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -707,6 +716,7 @@ QueryAST-aligned options for DataEngine.delete operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -773,6 +783,7 @@ QueryAST-aligned query options for IDataEngine.find() operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | @@ -867,6 +878,7 @@ QueryAST-aligned options for DataEngine.update operations | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 6dac1015ed2..f599774da6d 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -115,7 +115,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **submitted** | `Record` | optional | What the caller submitted, as sent (update only) — diagnostics only, never the persist image | | **dispatch** | `{ mode: Enum<'record' \| 'per-row'>; index: integer; scope: Record }` | optional | How this hook call relates to the caller's write (engine-produced) | | **session** | `{ userId?: string; actor?: string; organizationId?: string; accessToken?: string; … }` | optional | Current session context | -| **provenance** | `{ flowRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) | +| **provenance** | `{ flowRunId?: string; flowRootRunId?: string; attributedUserId?: string; performedByClientId?: string; … }` | optional | Server-stamped write provenance (never client-supplied, never an authorization input) | | **referentialFieldClear** | `boolean` | optional | Engine-produced marker: true exactly when this write is the engine's own referential cleanup (the set_null cascade UPDATE clearing — or, for multiple: true, removing the deleted member from — a lookup, tree or user field that references a record being deleted, where a user field takes part only when it declares its deleteBehavior). Absent on every other write, including a user hand-clearing the same field; read as `ctx.referentialFieldClear === true`. The declared projection of the operation-private `__referentialFieldClear`, carried across the sandbox boundary by contract; server-derived and never client-supplied. | | **referentialCascadeDelete** | `boolean` | optional | Engine-produced marker: true exactly when this delete is one the engine's cascade issued (the child delete removing a row that references a record being deleted through a relation whose deleteBehavior resolves to cascade, at any depth), in both phases of that delete. Absent on every other delete, including a user hand-deleting the same child and a delete a hook issues through ctx.api; read as `ctx.referentialCascadeDelete === true`. The delete twin of referentialFieldClear, carried across the sandbox boundary by contract; server-derived, never client-supplied, and with no operation-private spelling to read instead. | | **transaction** | `any` | optional | Database transaction handle | @@ -155,6 +155,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **flowRunId** | `string` | optional | Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request. | +| **flowRootRunId** | `string` | optional | Id of the root run of the flow-run tree `flowRunId` belongs to: the run the tree was started on, above every `subflow` child and `map` item run (equal to `flowRunId` on a run with no parent). Copied from `ExecutionContext.flowRootRunId`, which only the automation engine sets, beside `flowRunId`. Provenance, not authorization: lets a hook recognize a write by any run of one tree — the approvals plugin passes the runs of an approval through the hold it keeps between two steps on an object that declares `closedStates` (ADR-0162 D5). | | **attributedUserId** | `string` | optional | The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth `update-member-role` call the identity adapter executes as `isSystem`. ATTRIBUTION ONLY: the audit writer records it as `sys_audit_log.user_id`; no security middleware reads it, and it never becomes the subject the write is authorized as. | | **performedByClientId** | `string` | optional | [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, the `client_id` of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in `session.userId`. Copied from `ExecutionContext.performedBy.clientId`, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like `attributedUserId`: the audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork. | | **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 98014d1f7f0..7c60c56deea 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -172,6 +172,7 @@ const result = ApiMethod.parse(data); | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md index 9e7c7481736..7396a76ce26 100644 --- a/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md +++ b/docs/adr/0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md @@ -1,6 +1,6 @@ # ADR-0162: An object declares its closed states — in them the record and its master-detail lines are closed to change for every caller, a closed record is not deleted, and one lock read answers for pending approvals and for closed states -**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. +**Status**: Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's ruling of 2026-11-22 (ruling record [`7073676422`](https://github.com/objectstack-ai/objectstack/issues/32004#issuecomment-7073676422), item ② = C). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema key, no engine code, no route, no changeset; every mechanism below lands through a build card ([Execution](#execution-after-acceptance)). **Five points go past the ruling's words**; each is marked ▲ where it stands and all five are listed in [Points the ruling does not settle](#points-the-ruling-does-not-settle). The maintainer ruled on four of them on 2026-11-26 (ruling record [`7200732942`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7200732942)): each stands as written, and item ③ of the same batch is scoped to `readonlyWhen`. A second ruling the same day (ruling record [`7201405662`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7201405662)) adds one platform rule: an abandoned approval never writes a closed value ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). A third ruling the same day (ruling record [`7205949718`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7205949718)) settles the fifth point, in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not): the platform refuses the configuration that would leave a document reading a decision its approval did not finish. **Revised 2026-11-27** on two further rulings of the maintainer, made that day on the design of [Execution](#execution-after-acceptance) item 8 (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)): on a field the object closes on at an approval's outcome, each step's decision is written only when the approval is over for the record, and on an object that declares `closedStates` a document is held through every approval ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). After the contract review of the revision the seat read both rulings by their words (seat rulings [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661) and [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). The revision implements nothing either. · **Amended** (2026-11-29, option D on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311), maintainer 「D 统一校验,各入口都拒绝」): where a flow or an object is authored, the conditions an approval opens on are refused at every authoring door, and no longer only reported. One dated note under [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says how four passages of this record read after that ruling, and marks what in the note is not in the ruling's words. The refusal at the first request stays the rule, and the four passages are left as written. · **Revised again** (2026-11-29, on three rulings the maintainer made that day on the build of [Execution](#execution-after-acceptance) item 8, ruling records [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988) and [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), 「审批插件自己记下结论」, 「一小时后退回重提并通知」 and 「满一小时后结果通知一起写」): the approvals plugin keeps on the approval's own rows what it read of the approval's runs, and past an age bound a run that can no longer be read, or that never went on from the last decision, has stopped at the step last decided. Within the bound nothing is written for such a run, at the approval's last step as at every other. The revision was completed on 2026-11-30, when the build of item 8 had been reviewed. It adds one ruling of that day (ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330), 「A 维持现状,只写进文档」), by which a step log that has lost whole steps is read as it was kept, and the seat's readings that the build was reviewed on, each named as the seat's where it stands: which runs with no row are placed, two more states that are read as a run that cannot be read, and that a run is read as stopped only once two judgements in a row read it so, which makes the hour an hour and one pass of the reconciler more where no judgement read the approval within it. The reconciler's part of item 8, one passage of [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) and one sentence of [Consequences](#consequences) are revised where they stand, and nothing else is. One sentence of item 8 was false and is replaced: a process that dies while it advances a run leaves no row of that run behind, and not a history that says paused. - **Date**: 2026-11-26 - **Card**: [#36253](https://github.com/objectstack-ai/objectstack/issues/36253) (p2, `area:data`). Its rule, as the card carries it: @@ -202,7 +202,7 @@ The rule concerns a mirror field on which the object closes on `approved` or on A document under an approval of three steps therefore reads `pending` from its submission until the last step is decided and the flow behind that decision has run, and then reads `approved`, and is closed where the object closes on that value. On `main` it reads `approved` after each step. Where its second step rejects it, it reads `pending` until the flow behind the rejection has run, and then `rejected`. -**How the plugin learns that an approval is over.** At the decision it cannot know whether another step follows, which is why this record first turned the rule down. After it has resumed the run it can find out: it reads the run that carries the record, and asks its own table for a request of the approval on the record. It does so at every door that resumes or cancels a run of an approval: a decision, by a person or by the platform's own clock, a send-back, a resubmission, a recall, and the continuation of a restored run. It does not take the resume's own answer for it. That answer is for the request's own run. A child run that completes resumes its parent inside the same call, and the door is told of the parent's failure only where the parent's resume answered `stranded`; a parent that was cancelled, a store that could not be read and a resume that another process holds each end in a line of the log (`packages/services/service-automation/src/engine.ts#bubbleToParent`). Where the door cannot tell, because another process is advancing the run or the run cannot be read, it writes nothing. A decision leaves a mark on its request, a field the store can filter on, and a reconciler judges every marked request the door did not: after a process that died, after a run that was cancelled, after a parent run that is gone. The mark says that what follows the decision has not been judged yet. Every decision of an approval on an object that declares `closedStates` leaves it, also where the decision is written at once, because the hold, below, is read off it. [Execution](#execution-after-acceptance) item 8 has the means. The reconciler is what ends an approval that nobody is at the door for, so an approval on an object that declares `closedStates` opens only on a host that runs one, below. +**How the plugin learns that an approval is over.** At the decision it cannot know whether another step follows, which is why this record first turned the rule down. After it has resumed the run it can find out: it reads the run that carries the record, and asks its own table for a request of the approval on the record. It does so at every door that resumes or cancels a run of an approval: a decision, by a person or by the platform's own clock, a send-back, a resubmission, a recall, and the continuation of a restored run. It does not take the resume's own answer for it. That answer is for the request's own run. A child run that completes resumes its parent inside the same call, and the door is told of the parent's failure only where the parent's resume answered `stranded`; a parent that was cancelled, a store that could not be read and a resume that another process holds each end in a line of the log (`packages/services/service-automation/src/engine.ts#bubbleToParent`). Where the door cannot tell, because another process is advancing the run or the run cannot be read, it writes nothing. A decision leaves a mark on its request, a field the store can filter on, and a reconciler judges every marked request the door did not: after a process that died, after a run that was cancelled, after a parent run that is gone, after a run whose history is gone or does not name every run it started, after a decision whose run never went on, and after a tree of more runs than it can read in full. For a run it can no longer follow, three rulings of 2026-11-29 give the rule. The first two are in ruling record [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988). The maintainer chose on two decision cards, verbatim and untranslated. On 「审批的流程运行记录被清理或读不到时,单据怎么判?」, how a document is judged when the run records of its approval were cleaned up or cannot be read: 「审批插件自己记下结论」, the approvals plugin records the conclusion itself. On 「决定已记下但流程没接着走(服务中断),单据怎么处理?」, what becomes of a document whose decision is recorded while its flow did not go on, in an outage: 「一小时后退回重提并通知」, after one hour it is put back to be submitted again, and a notice is sent. As the ruling record states them: the plugin keeps what it read. At each door, and as each request opens, it records on the approval's own rows what the runs it could read showed, which is whether the approval has, so far, a failure between two steps that no later request answered. A later judgement does not read those runs again, so a history that was trimmed and a process that died do not leave a document on `pending`. A run the plugin never read is placed by the step last decided, and that placement and the second ruling are one rule: past an age bound, with no request of the approval open on the record, a run that cannot be read, or that is still parked at the node of the request last decided, has stopped at that step. Where a step can follow the step it stopped at, the approval ended between two steps and is abandoned, as the bullet on a run that ends between two steps has it, below, and a run that is still parked is cancelled. Where none can, the approval has finished, and where the run never went on from that last decision the administrators are told. The third ruling is in ruling record [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), and it settles what the first two leave open at the approval's last step: when the outcome is written, and whether the administrators are told where the run cannot be read. The maintainer chose on one decision card, verbatim and untranslated. On 「最后一步已批准但流程没接着走时,审批结果什么时候写到单据上?」, when the outcome of the approval is written to the document where the last step was approved and the flow did not go on: 「满一小时后结果通知一起写」, once the full hour has passed the outcome and the notice are written together. As that record states it: nothing is written for such a run within the bound, at the last step as at every other. Once the bound has passed, the outcome and the administrators' notice are written in one stroke, and the notice also covers a last step whose run has no row. It is one rule, with no special case for the last step. For this record that means: a run that has not left the node of a decided request has not gone on from the decision, and within the bound it is not read as parked at a pause that no step can follow, above. Four things stand beside the three rulings, and [Execution](#execution-after-acceptance) item 8 carries each where it applies. One is a ruling of 2026-11-30, in ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330). The maintainer chose, verbatim and untranslated, 「A 维持现状,只写进文档」, A, keep what is built and only write it into the documentation: a step log that has lost whole steps carries no mark of it, the plugin reads what the log kept, and that is a stated limit of this release. The other three are the seat's, and none is a ruling. The seat reads "a run the plugin never read", in the first ruling, as a run that no run the plugin read speaks for: a run with no row counts as passed where a run the plugin read went on past the step that names it, and going on along a failure route is not going on past the step (seat reading [`7257555103`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257555103), which ruling record [`7257604888`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257604888) lists for the rebuild). The seat reads as runs that cannot be read a run whose step log does not name every child run it started (seat ruling [`7258590209`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7258590209)) and a tree of more runs than the judgements can read in full (the seat's note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) on the review of item 8's build). And the seat has a run read as stopped, past the bound, only once two judgements in a row read it in the same state, because the hour runs from the mark and a run that is being resumed reads as a run that stopped does (the same note, on a finding of review [`7269135624`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269135624)). The order changes when an end the rulings give comes, and not which end it is. The option the maintainer chose in the third ruling read 「一条规则、不分最后一步;这种少见情况单据最多显示审批中一小时,之后结果和管理员通知一起落。读不到运行记录的最后一步也通知。」: one rule, with no special case for the last step; in this rare case the document shows in approval for at most one hour, and after it the outcome and the administrators' notice land together; a last step whose run records cannot be read is notified as well. The hour holds wherever a judgement read the approval's state within it. Where none did, it is the hour and one pass of the reconciler more, which is one sweep interval, five minutes by default, and more only in the cases item 8 names. That holds for every marked approval, one that holds a decision back included, and nothing is written early. The reading is the seat's and asks no new ruling (seat note [`7270603869`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7270603869), whose third line the seat's correction [`7272498941`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7272498941) replaces: the note first gave the pass more only to approvals that hold nothing back). The mark says that what follows the decision has not been judged yet. Every decision of an approval on an object that declares `closedStates` leaves it, also where the decision is written at once, because the hold, below, is read off it. [Execution](#execution-after-acceptance) item 8 has the means. The reconciler is what ends an approval that nobody is at the door for, so an approval on an object that declares `closedStates` opens only on a host that runs one, below. **On an object that declares `closedStates`, a document under approval is held for the whole of the approval.** Ruled 2026-11-27 at 04:50Z (the same ruling record): 「随新能力一起全程锁」, locked the whole way, and shipped with the new capability. The ruling record states the rule: 「只对声明了 `closedStates` 的对象,从提交到审批结束都锁住,随键一起发布。」, only on objects that declare `closedStates`: held from the submission to the end of the approval, and shipped with the key. The option the maintainer read says 「只对声明了关闭状态的对象,从提交到审批结束别人都改不了」: only on objects that declare closed states, from the submission to the end of the approval nobody else can change the document. The seat reads those words as they stand (seat ruling [`7211509661`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211509661)), and the hold below is that reading. @@ -241,6 +241,29 @@ An approval none of whose steps mirrors onto a field the object closes on is ask **The approval is judged whole, once, at its first request.** That is the first point at which the objects and the flows are certainly all in hand: they are published apart, and any of them can change after the others. The node reads the approval from its definition: every approval step of the flow the record's run was started on, and of every flow that a `subflow` or a `map` in it names, to any depth. It judges each step on that step's own mirror field and on each object the step can act on: the object of the run's record, and under a `map` the object that node names for its items as well. Every step has therefore been judged before the first request is written, one that opens later on another record or another object too. A first step that names no mirror field does not open the approval unjudged: where another step that can act on the same object is one the conditions concern, the approval is refused for the step that names none. A later request of the same approval is not judged again: refusing it would end the approval between two steps, after steps that were already decided. A request that the plugin cannot place as first or later is not judged either, for the same reason, below. Where a part of the approval cannot be read ahead, a flow that a node names and the plugin cannot read, the approval cannot be judged, and its first request is refused. The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule. The rule holds for an approval of one step as for one of several, since a single step fails too, on a decided document that is sent for approval again. In an application where no object declares the key, nothing is read and no approval is refused. +> **Note (2026-11-29, ruling record [`7253749311`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7253749311) on [#37766](https://github.com/objectstack-ai/objectstack/issues/37766), option D) — where a flow or an object is authored, the conditions are refused at every authoring door, and no longer only reported.** Card #37766 builds [Execution](#execution-after-acceptance) item 7. One item of it asked what an author is told before the first request: an error, or only a notice. The seat put that to the maintainer as a choice, and the maintainer chose the option that reads, verbatim and untranslated, 「D 统一校验,各入口都拒绝」, D: one check, and every door refuses. The line under that option, as the maintainer read it, reads in full 「写文件的项目在校验和构建时、设计器和 AI 在发布时都报错并说明缺什么。现有草稿 PR 的入口部分作废,重做一个 PR;您批一条决策记录修订。」: a project written in files gets an error at validate and at build, and the designer and an AI author get one at publish, each error saying what is missing; the door half of the draft PR is set aside and the work is redone as one PR; the maintainer approves one amendment of a decision record. As the ruling record states it: at authoring the gap is an error, and a notice alone is not the answer; the refusal is made at every authoring door, from one check in the platform's shared rule table; this record is amended by one dated note, and [ADR-0094](./0094-sys-permission-set-pure-projection.md) is not amended. This note is that amendment. +> +> Four passages of this record are read with this note, and each is left as written. +> +> - **The paragraph above**: "The same conditions are reported where a flow or an object is authored, wherever the parts are in view together; that report is early notice, and the refusal at the first request is the rule." For "reported" read "refused", and for "that report is early notice" read "that refusal comes early". The rest of the sentence stands. +> - **[Execution](#execution-after-acceptance) item 7, the check**: "The same conditions are reported at authoring wherever the parts are in view together." For "reported" read "refused". +> - **[Points the ruling does not settle](#points-the-ruling-does-not-settle), the list under the third ruling of 2026-11-26**: "the refusal is made when an approval opens and reported at authoring, and is not made at publish, where the option's words allow either". Read: the refusal is made when an approval opens, and at authoring too, publish included. Not refusing at publish was this record's choice inside that ruling, and the ruling of 2026-11-29 replaces it. The other points of the list are untouched. +> - **[Alternatives considered](#alternatives-considered)**: "Refuse the configuration only where the object or the flow is published." It stays not chosen as the rule, for the reason the entry gives: a publish check sees the pair only some of the time. For its last sentence, "It is kept as early notice.", read: it is kept as a refusal beside the rule. +> +> The rest of this note is not in the maintainer's words. The ruling record lists each point below as carried from the decision analysis ([`7252928345`](https://github.com/objectstack-ai/objectstack/issues/37766#issuecomment-7252928345)) or as not ruled. They are the seat's proposals, built in the change that carries this note, for the maintainer to accept with it or strike. +> +> - **The first request stays the rule** (carried from the analysis). The refusal at authoring is added to it and replaces nothing. An authoring door has the parts of an approval in view only some of the time, and the first request has them all. +> - **One judge** (carried from the analysis; where it lives is the seat's choice). The first request and the rule ask the same code (`packages/metadata-core/src/approval-opening.ts#judgeApprovalOpening`, `#judgeApprovalOpeningSync`): the first request through the entry that awaits each flow it reads, the rule through the entry that reads a stack in hand. Both entries drive one walk of the approval's flows and one judging function, so the conditions are written once. The two verdicts can still differ, because the two doors do not have the same things in view: the last point below says where. +> - **Released with the key** (carried from the analysis). The refusal at authoring is part of item 7's check and is released as item 7 is: the release that first publishes `closedStates` carries it. +> - **The rule** (the seat's). `validateApprovalClosedStates` (`packages/lint/src/validate-approval-closed-states.ts#validateApprovalClosedStates`) reports the finding `approval-closed-state-gap` at severity `error`. It is a member of the reference-integrity suite (`packages/lint/src/reference-integrity-suite.ts#REFERENCE_INTEGRITY_RULES`), which is one entry of the shared author-time rule table (`packages/lint/src/authoring-rules.ts#AUTHORING_RULES`), so `os validate`, `os build` and `os lint` run it over a project's stack. The approvals plugin registers no gate of its own, and the authoring-gate seam that ADR-0094 records gains no member. +> - **The runtime publish door** (the seat's). The write path behind Studio, REST `/meta` and MCP runs the rule on a `flow` write and on an `object` write: at an active save, at a draft's promotion, at a restore, and for each draft of a package publish. It refuses with `INVALID_METADATA` (422), a code that door already gives. A draft is not refused, because no rule of the table refuses a draft there. On an `object` write the door judges the live flows of the written object's package against the written object, and charges the write only with a gap it adds: a gap the stored universe already holds is not that write's. In a package publish each draft is judged against the batch's objects, and a flow the batch redrafts is judged as its draft, at its own write. A package that declares `closedStates` and repairs its flow in one publish therefore passes, and one that declares it without repairing the live flow is refused (`packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts`). +> - **What an authoring door does not judge** (the seat's). At authoring there is no run. The first request judges on the object its root run was started on. The rule reads an object off the flow's definition instead (`packages/lint/src/validate-approval-closed-states.ts#approvalRootObjectsOf`): the `start` node's object where the flow declares one, and only where it declares none, the object of each start input that is a record, each read as a record the flow can be started on. It judges each flow in view as the root of an approval, on the objects so read. A door refuses only for what it has in view, and not for the following. The first request has each of them in hand and judges it: +> - a run on a record of an object the rule did not read: a flow that declares no object, neither a `start` object nor a record input, and is started by an action or by name on a record, is judged at authoring with no object for the run's record; and a flow that declares only record inputs can be started on a record of another object, on which the first request then judges; +> - a flow that is not in view: one that a `subflow` or a `map` names and the stack does not hold; on a `flow` write at the runtime door, every flow but the written one, the flows it calls and the flows that call it included; on an `object` write, every flow of another package; +> - a pause by a node whose type the spec does not list as pausing (`packages/spec/src/automation/flow.zod.ts#FLOW_PAUSE_CAPABLE_NODE_TYPES`, a `wait` and a `screen` among them): at every authoring door, the runtime door included, such a node counts as one that does not pause, a plugin's type too, because the rule is handed none of the engine's descriptors; +> - the host's `job` service, which is a fact of the deployment and not of what is authored; +> - an object that is not in view. + **What the conditions do not reach.** The platform reads ahead what can be read: a field's options, with the `visibleWhen` of those the mirror writes for a request's status, and its `readonlyWhen`; an object's closed values; the one move of a `state_machine` rule that a lock depends on; and the nodes of the approval's flows, with each step's mirror field, every node that pauses, and every `map` that holds an approval step. An author who puts a `state_machine` rule on the mirror field owes the mirror its other moves as well, from one status to the next and out of `pending` and `returned` when a request is abandoned. A move the rule refuses leaves the field on the status it holds, which is then an open one, and it is a refused write of the mirror like any other, below. Four things cannot be read ahead. When this record was merged, each of them could leave a record on an earlier step's outcome, closed, with its approval unfinished. For the first three it fixed what must hold, that the record is not left closed on a value its own approval wrote, and left the means to a card of its own ([Execution](#execution-after-acceptance), item 8). The ruling of 2026-11-27 meets that bound for the three at its root: the outcome is not on the record before the approval is over, so none of them can leave it there. What each leaves in its place is stated here, as the seat ruled it on that card's design note (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)). The key is still not released before that card is built. - **A rule or a hook of the app's own that refuses a write of the mirror.** A rule of another kind than `state_machine`, or a hook, can turn on the record's data, so no reading of a definition shows what it will do. A `visibleWhen` on an option that is not a request's status can refuse a value the mirror puts back, and it is held to the same. On `main` every such refusal is logged and swallowed, on every write of the mirror. On a field the object closes on at `approved` or `rejected` none is swallowed, and what follows depends on the write. @@ -397,7 +420,7 @@ Nothing below starts before this record is Accepted. The seat files the cards; t 8. **The status mirror on a closing field: the outcome when the approval is over, an approval that does not finish, and the hold.** The child card the recommendations adopted on 2026-11-26 give the mirror's failed write ([`7202242844`](https://github.com/objectstack-ai/objectstack/issues/36253#issuecomment-7202242844)), filed as [#37767](https://github.com/objectstack-ai/objectstack/issues/37767). When this record was merged, [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) fixed what the card delivers and left it the means: on a field the object closes on, nothing leaves a record closed on a value its own approval wrote and did not finish. The card's design note set the means out, the maintainer ruled its two questions on 2026-11-27, and the seat ruled the rest (ruling record [`7210179412`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7210179412)). [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) now states the rules, and the parts below are their scope. The parts on a refused write and on the outcome are kept to an approval the conditions concern. The mark, the reconciler and the hold reach every approval on an object that declares `closedStates` (seat ruling [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). An object that declares no closed value behaves as it does today. Item 1 waits for all of them, the hold included: the key is not released before this item is built. The seat files it as one card or as several. - **No refused write is swallowed.** On a field the object closes on at `approved` or `rejected`, a write of the mirror that a rule or a hook of the app refuses, or a `visibleWhen` on an option, is reported: an `error` line in the log, a line with no actor on the request's timeline, and a notice to the organization's administrators. A refused `pending` at an approval's first request refuses the opening. The request's row is written first and the `pending` second, and on a refusal the row is voided as `cancelled`; the other order could leave a decided document on `pending` with no request. Its tests pin, for each transition of a request, the value the field keeps when the write is refused. - **The outcome when the approval is over.** On a field the object closes on at `approved` or `rejected`, every step's decision is held back, whichever of the two the object closes on. A decided request carries a mark: one new field of the request, which the store can filter on, set in the update that records the decision and cleared when the approval has been judged (`Clause-②: yes`). The mark is set at every decision of an approval on an object that declares `closedStates`, also where nothing is held back, because the hold is read off it. After every resume, and after the resume or the cancel a recall makes, the door reads the run that carries the record and asks its own table for a request of the approval on the record. It has four answers. Finished: it writes the decision of the approval's latest request on the record, where that request was decided. In progress: it writes nothing. Ended between two steps: it abandons the approval as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says, puts the field back by item 7's order, marks the approval abandoned on the request, and leaves a line with no actor. Cannot tell yet, for a run another process is advancing or one it cannot read: it writes nothing and leaves the mark. In an approval that holds nothing back, the first and the third answer both end the hold: the mark is cleared and nothing is written. The door places a stop or a pause against the set item 7 stamps. It reads the run's step log for a failure the flow routed, and keeps a durable note on the approval's latest request where a later step could not open, so that the judgement does not depend on how that failure was routed. The door that continues a restored run refuses an approval marked abandoned, and tells the operator to cancel the restored run. A recall, an override and the dead-run sweep clear the mark on the approval's earlier requests. Its tests include: a first step approved, a second recalled, and a run that then completes, after which no `approved` is written; the same for a returned request that is recalled in its revise window; a second step that rejects on an object that closes on `approved` alone, and a first step that approves on an object that closes on `rejected` alone, in each of which the field keeps `pending` until the approval is over; a `wait` after the last step, where the outcome is written as the run parks; a node that fails after the last step, where the outcome stands; an item of a `map` that is a record, whose outcome does not wait for the later items and is not undone by a later item's failure; a next step that fails to open, on an empty slate and on a request of another approval already pending on the record, where the field keeps that approval's `pending`; a later step that fails to open with a `fault` edge to an end, which is abandoned, and with a `fault` edge to a second step that opens, which is in progress; another node that fails between two steps with a `fault` edge to an end, which is abandoned; and that node's failure handled in a `try_catch` region, after which a gateway ends the flow, which is finished. - - **The reconciler.** For an approval on an object that declares `closedStates` it takes the place of the reader of stranded requests (`packages/plugins/plugin-approvals/src/approval-service.ts#inspectStrandedRequests`). It scans the mark, oldest first, so that its scan is bounded, and judges each marked request as the door would have. It places three states that reader skips today: a cancelled run; a run whose history says paused while its pause is gone, which a process that died in a passage leaves for good; and a run still parked at a `subflow` or a `map` whose child has ended, which nothing will resume. The last two need an age bound, which the build chooses and states. It writes in the name of the request's recorded decider, as the door would have: a write with no actor would leave a flow that reacts to the change, and runs as the user, without an identity. It tries a refused outcome or put-back again while the mark stands, and sends the administrators' notice. Where nothing was held back it clears the mark and writes nothing. For a record that was deleted it clears the mark and writes nothing, and it neither tries again nor notifies. On a host with no `job` service the first request of every approval on an object that declares `closedStates` is refused, with an error that says what is missing, also where the approval's field closes on nothing. Its tests include a parent run that is cancelled while its child's request is pending; a process that dies between a decision and the write of its outcome; an approval whose field the object does not close on, whose hold the reconciler ends; a host with no `job` service, on which such an approval is refused as well; and a record deleted in a passage, whose mark is cleared once. + - **The reconciler.** For an approval on an object that declares `closedStates` it takes the place of the reader of stranded requests (`packages/plugins/plugin-approvals/src/approval-service.ts#inspectStrandedRequests`). It scans the mark, oldest first, so that its scan is bounded, and judges each marked request as the door would have. It places seven states. That reader places none of them: it reports a run that has no row and changes nothing, and it passes over a run that was cancelled or is paused. The seven are a cancelled run; a run whose history says paused while its pause is gone; a run that has no row at all, where no run the plugin read speaks for it; a run still parked at a `subflow` or a `map` on a child run that will not resume it; a run still parked at the node of the request last decided, whose decision is recorded and which never went on; a run whose step log is cut, so that it does not name every child run the run started; and a tree of more runs than the judgements can read in full. The list was revised on 2026-11-29, on the maintainer's three rulings of that day (ruling records [`7256254988`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7256254988) and [`7257388557`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257388557), stated in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). It had three states, the first, the second and the fourth, and it said of the second that a process that died in a passage leaves it for good. That is not so. A resume takes the pause away before it runs anything behind it (`packages/services/service-automation/src/run-resume.ts#resumeInternal`), and the history keeps a lasting row only for a run that has ended (`packages/services/service-automation/src/run-history.ts#recordLog`). Only a process whose own memory still holds the run's paused entry reads the second state. After a restart, and in a process that never held the run, a run that a process died advancing has no row at all (`#getRun`), which is the third state, and a run that ended is in it too once the history has trimmed its row (`packages/services/service-automation/src/suspended-run-store.ts#DEFAULT_MAX_TERMINAL_RUNS_PER_FLOW`). Both were read on the trunk at `37e97a8366`. The sixth and the seventh state were added on 2026-11-30, when the build of this item had been reviewed, with the readings of the other states that follow. Each is given to the record it comes from, and those that are the seat's are not rulings. A run with no row is in the third state only where no run the plugin read speaks for it. Where a run the plugin read went on past the step that names such a run, the run counts as passed at that step and is not placed: it is kept as ended, and the approval is judged by its other runs, at the door or within the bound, with no notice. A run went on past a step where the step succeeded and the run then reached an end of its flow, or logged a later step and is not parked at that step. A step that failed is never passed, also where the flow routed its failure and went on. A run whose step log is cut speaks for no run, and a run the plugin had read to its end over a child run it had not read is not passed once its own row is gone, because nothing names that child any more. That a run the plugin read speaks for the child runs it went on past is the seat's reading of the first ruling, and not a ruling (seat reading [`7257555103`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257555103), its second point), and that going on along a failure route is not going on past the step is the pin with which ruling record [`7257604888`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7257604888) lists the reading for the rebuild. What going on past a step means in a run's log, and the two bounds on a cut log and on a run whose own row is gone, are the build's, and each narrows the reading toward the ruling's own rule. [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) keeps the ruling record's sentence on a run the plugin never read, and the reading says which runs those are. The fourth state is a run parked on a child run that has ended, that has no row, or that has itself stopped in the second or the fourth state. It covers a `map` whose items are records. An item run of such a `map` carries another record, and its steps are that record's own approval, so the plugin reads none of them: it reads only whether the item run has ended, which it has once it is in a terminal status. [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) leaves no `map` with an approval step in its body in an approval the conditions concern, unless none of its items is a record, and no other pause between two steps of one. So a run parked at a `map` on an item run that carries another record belongs to an approval that holds nothing back. The sixth state is a run whose step log is cut. Two logs are read so. One has a step that carries the engine's mark `childRunIdsTruncated`: the step started more child runs than the 200 a step names, or the history row shed the step's list to fit its size. The other is the log of a run that has ended whose history row cannot be shown to keep every step the run logged: it keeps fewer than the run's summary counts, or the summary gives nothing to compare. The child runs such a log does name are still read, and it speaks for none of them. The seat ruled the state (seat ruling [`7258590209`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7258590209)): within the bound the plugin cannot tell, and past it the approval is placed by the step last decided, with the notice at a last step. One limit stands beside it, by the maintainer's ruling of 2026-11-30 (ruling record [`7268216330`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7268216330), stated in [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)): a log that loses whole steps carries no mark. The engine keeps 200 steps of a longer log, and nothing tells the plugin which steps that compaction dropped, so it reads what the log kept, and a child run named only by a dropped step reads as one the run went past. A failure between two steps in such a child run is then not seen, and the approval can be written as finished with no notice. That is a stated limit of this release, and no engine change follows from the ruling. A history row that was halved over its size cap, or stored as null, is still told from the run's summary and is read as cut (the seat's line on that ruling, in its note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) on the review of the build). The seventh state is a tree of more runs than the judgements can read in full. One judgement reads at most 200 runs beside those the plugin keeps as read to their end, and the next judgement reads on from what was kept. Within the bound the plugin cannot tell of a tree it has not read to its end. Past the bound a judgement reads on only while it keeps a run the approval had not kept, and the kept list holds 200 runs, so at most 200 judgements read on. The one that keeps no further run cannot finish the tree, and the approval is placed by the step last decided, as one whose run the plugin never read. The seat accepted that rule with its two costs (the same note, under seat ruling `7258590209`). A tree the judgements cannot finish is placed without having been read in full, and a tree of about 399 runs can already be one, because a judgement reads the runs it starts from before the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end. The last six states need an age bound. The build chooses it and states it, and it chose one hour from the mark, the hour the maintainer's choices name: every mark the approval carries has stood that long. Within the bound the reconciler writes nothing for them and leaves the mark, as the door does, because the run may still be going on in another process. That holds at the approval's last step as at every other, which the third ruling settles. The read tells a run with no row from a store that did not answer, and where the store did not answer nothing is written at any age. Past the bound, with no request of the approval open on the record, each of the six is read as a run that has stopped once two judgements in a row have read it in the same state: the same state of the same run, and for a run parked on a child run, the same child. One reading does not show it. The hour is counted from the mark and not from the run's last movement. A run the engine is resuming reads as the second state or as the third, for the reason given above, and a run whose child run has just ended reads as the fourth until the engine resumes it. An approval whose flow waits between two steps for longer than the hour, as its author meant it to, would be read as stopped in the first instant of its next resume. The state a resume leaves is gone when the resume is done, and the state a dead process left reads the same again. So every judgement keeps the states it read on the approval's own rows, in place of those kept before, a door's judgement and one within the bound included; a door that leaves a request open keeps none, because a run parked at the step of an open request has not stopped; and the judgement that reads a state for the first time writes nothing on the record. This is the seat's order on the review of the build, and not a ruling (review [`7269135624`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269135624) raised it, the seat's note [`7269166540`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7269166540) ordered it, and review [`7270552441`](https://github.com/objectstack-ai/objectstack/pull/38634#issuecomment-7270552441) read it as built). Only an approval that holds nothing back can wait so: [D5](#d5--who-is-bound-every-caller-a-system-context-is-not)'s condition that no flow of the approval pauses between two steps refuses a `wait`, a `map` over records that are approved one by one, and a child run that pauses there, in every approval the conditions concern. A placement in an approval that holds nothing back ends the hold and writes nothing. What the rule leaves is two judgements in a row that each fall inside a resume of the same run, one resume or two, and that is the engine's to end, by reporting a run it is advancing (card [#38708](https://github.com/objectstack-ai/objectstack/issues/38708)). A reading that could not be kept leaves on the request the reading kept before it, and the next judgement stands on that one; where none was kept nothing is placed, so an approval whose reading is never kept is held with no end, as one whose store does not answer is. The hour of the maintainer's choices therefore holds wherever a judgement, a door's or the reconciler's, read the state within it: the first pass after the hour places the run. Where none did, that pass reads the state and keeps it, and the pass after it places the run, which is one pass of the reconciler more. A pass comes once in each sweep interval, which is five minutes by default (`packages/plugins/plugin-approvals/src/approval-service.ts#ESCALATION_SCAN_INTERVAL_MS`), and where more requests are marked than one pass reads, the oldest marks are still read on every pass and the others once in each turn of the scan. A reading ends at a run that reports paused with its pause gone and keeps only what it read by then, so each run of a tree in the second state can cost a pass more; the other states of a tree are read in one reading, kept together, and stand together. The seventh state takes the passes that read on. The seat states this against the option text of the third ruling, which named one hour and which [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) quotes, and asks no new ruling (seat note [`7270603869`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7270603869), with the seat's correction [`7272498941`](https://github.com/objectstack-ai/objectstack/issues/37767#issuecomment-7272498941) of its third line: the pass more can fall on any marked approval, one that holds a decision back included). The second has stopped where its own log ends, and the fourth where it is parked, as before. The other four are placed by the one rule of the rulings, at the step last decided: the third and the fifth as the rulings state it, and the sixth and the seventh as runs that cannot be read, by the seat's ruling and acceptance above. Whether a step can follow the step last decided is asked in the request's own flow: the flow of the run still parked at that step, and otherwise the flow the request records. Where the set of nodes the request carries ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)) names that flow, a node of another flow of the approval that carries the step's id does not answer for it. Where the set names no such flow, or the request records none, the id alone decides, which can only cost a resubmission. What came before that step the reconciler does not read again, because the plugin keeps it: at each door, also one that leaves a request open (the first point of the seat's reading), and as each request opens, it records on the approval's own rows whether the approval has, so far, a failure between two steps that no later request answered. It keeps there, too, which runs it has read to their end, so that a judgement reads on from the one before it. Where a step can follow the step last decided, the approval ended between two steps and is abandoned as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) says. Where the approval holds a decision back, the run still parked in the fifth state is then cancelled, and with it every run above it that waits on it, up to the run that carries the record, through a `map` as through a `subflow`, so that nothing resumes the approval on a record that was put back. A `map` in that chain has items that are not records, so its items are steps of this one approval, and the batch is cancelled with its item and does not go on to the next. The cancel is not tried again once the put-back has landed: where it fails, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it, as [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) has it. Where the approval holds nothing back, nothing is written, told or cancelled: the mark is cleared and the run stays parked. Where none can, the approval has finished: its outcome is written and the administrators are told in one stroke, in the third state as in the fifth, as the third ruling has it, and in the sixth and the seventh as well. The notice goes only on the pass whose write of the outcome landed: a refused write sends no such notice, and the pass on which the write lands sends it. It goes out on the topic `approval.flow_not_continued` and says that the flow could not be seen through to its end after its last step, because the flow's nodes behind that last decision did not run, or cannot be shown to have run. In the sixth and the seventh state the flow may have gone on where the plugin could not read it, so the notice asks for a check and states no failure. In the fifth state the pause is left, so that an operator can still continue the run (`packages/plugins/plugin-approvals/src/approval-service.ts#continueRestoredRun`). It writes in the name of the request's recorded decider, as the door would have: a write with no actor would leave a flow that reacts to the change, and runs as the user, without an identity. It tries a refused outcome or put-back again while the mark stands, and sends the administrators' notice. Where nothing was held back it clears the mark and writes nothing: no outcome, no put-back, no notice and no cancel, also where it placed a run, and a line in the log says what it concluded. For a record that was deleted it clears the mark and writes nothing, and it neither tries again nor notifies. On a host with no `job` service the first request of every approval on an object that declares `closedStates` is refused, with an error that says what is missing, also where the approval's field closes on nothing. Its tests include a parent run that is cancelled while its child's request is pending; a process that dies between a decision and the write of its outcome; a run that has no row, past the bound, where a step can follow the step last decided, which is abandoned, and where none can, whose outcome is written and whose administrators are told; a run that has no row under a run that went on past its step, which is passed, so that the approval finishes at the door and nobody is told, and the same under a run that went on along a failure route, which is held and then placed; a decision whose run never went on, before the last step, where the approval is abandoned and the parked run cancelled, with the batch above it where it is an item run of a `map` whose items are not records, and at the last step, where the outcome is written once the bound has passed, the administrators are told and the pause is left; a step that started more child runs than it names, which is held to the bound and then placed; a tree of more runs than the judgements can read in full, which is placed once a judgement keeps no further run; a run parked at a `map` whose items are records, on an item run that has ended and on one that has not; a run the engine is resuming past the bound, which is not placed, and a state that two judgements in a row read, which is; a judgement whose reading cannot be kept, which places nothing; a step last decided whose id a node of another flow carries; an approval that holds nothing back in which a run is placed, where nothing is written, told or cancelled; an approval whose field the object does not close on, whose hold the reconciler ends; a host with no `job` service, on which such an approval is refused as well; and a record deleted in a passage, whose mark is cleared once. - **The hold.** On an object that declares `closedStates` the pending lock's reads honour the mark, so that the record and its lines are held through every passage of every approval, with the passes and the limits [D5](#d5--who-is-bound-every-caller-a-system-context-is-not) gives: the revise window, a caller's delete of the record, a system context, a write that carries only the mirror field, and the approval's own runs, known by their root run. In a passage those reads do not ask the node's `lockRecord`. The one lock read of item 2 answers `approval` in a passage. The approvals-family read is not touched and answers as published. This part settles two things the design note left open. The first is how the lock reads a writer's root run, and with it which indirect writes carry a run of the approval: a hook of the app that writes back to the record, and a cascade from another object. One that carries none is refused, and the build pins each case. The second is how the approval of a record that is deleted in a passage ends, where `main` cancels a pending request and no other (`packages/plugins/plugin-approvals/src/approval-service.ts#cancelForDeletedRecord`): the approval is marked abandoned, its marks are cleared and nothing is written, so that no mark of a deleted record stands for good and the reconciler has nothing to try again or to notify for. Its tests include a caller's write between two steps and after the last decision, each of which is refused; the same on an approval whose field the object does not close on, and on an object that closes only on values of its own; a write by a node of a parent run after its child's step is decided, which lands; a line write in a passage; a node that declares `lockRecord: false`, under which a caller's write lands while its request is pending and is refused after its decision; a revise window that follows an earlier step's decision, which is open to every caller who may edit; a caller's delete in a passage, which lands and ends the approval; a hook's write-back and a cascade in a passage, each with the approval's run and without it; the approvals-family read in a passage, which answers as on `main`; an approval that opened before the object declared the key, which is not held; and a process that dies in a passage, after which the reconciler ends the hold. - **The docs.** The approvals guide says what an author and an administrator see in each case: that the document reads `pending` until its approval is over; that a flow which fires on `approved` fires once on such an object, when the approval is over; that a node after a decision reads `pending`; what a refused write and an abandoned approval look like on the request; that on an object that declares `closedStates` every approval holds the document between its steps, whatever its field and whatever a node's `lockRecord` says, and that a pause there holds it for as long as it lasts; that a client which asks only the approvals-family lock read is not told of that hold; and that every approval on such an object needs a host with a `job` service. @@ -533,7 +556,7 @@ Left open on purpose, each a later decision if it is ever wanted: - An approval on an object that closes on `approved` or `rejected` is refused when it opens until five things hold: `pending` is declared and open and `returned` is open, a `state_machine` rule on the field lets the closed outcome move to `pending`, the field carries no `readonlyWhen` and its options for a request's statuses no `visibleWhen`, every step that can act on the object names the one field, and no flow pauses between two steps. An object that closes on `pending` or on `returned` runs no approval onto that field, and an approval the platform cannot read whole is refused ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). - Every approval on an object that declares `closedStates` needs a host that runs a `job` service, also one whose field closes on nothing (seat ruling [`7211531658`](https://github.com/objectstack-ai/objectstack/issues/37817#issuecomment-7211531658)). With none, nothing would end an approval, or its hold, that nobody is at the door for, and the approval is refused when it opens. An object that runs approvals on a host without that service cannot declare the key until the host has one. - A fault between two approval steps costs a resubmission, and every step already decided is decided again: a fault at step four of five costs four approvals. The platform abandons the approval at once and does not wait for an administrator ([D5](#d5--who-is-bound-every-caller-a-system-context-is-not)). -- A document reads `pending` for longer than it does on `main`. Its outcome waits for the flow behind the last decision, and, where the door cannot tell that the run has ended, for the reconciler's next pass. One status mirror has two timings: on a field the object closes on at `approved` or `rejected` every decision waits for the end of its approval, and every other status is written at once. That includes a decision the object does not close on. Where an object closes on `rejected` alone, an approved step shows only when the approval is over, and a view or a flow that reads the field between two steps reads `pending`. +- A document reads `pending` for longer than it does on `main`. Its outcome waits for the flow behind the last decision, and, where the door cannot tell that the run has ended, for the reconciler: for its next pass where the run can then be read, and, in the six states [Execution](#execution-after-acceptance) item 8 holds to its age bound, for that bound, which is an hour from the mark, and for one pass more where no judgement read the approval's state within that hour. What ends the wait there is the outcome, or the put-back where the approval ended between two steps. One status mirror has two timings: on a field the object closes on at `approved` or `rejected` every decision waits for the end of its approval, and every other status is written at once. That includes a decision the object does not close on. Where an object closes on `rejected` alone, an approved step shows only when the approval is over, and a view or a flow that reads the field between two steps reads `pending`. - A caller who can edit a document between two approval steps on `main` cannot on an object that declares `closedStates`: the hold keeps it, in every approval on the object, whether or not the approval closes anything and whatever its nodes' `lockRecord` says. An author who declares a closed value of the object's own, `paid`, changes how an approval that has nothing to do with that value behaves between its steps. A node that follows the last step after a pause, in a flow that runs as the user, meets a closed document. - A pause between two steps of an approval the conditions do not concern holds its document for as long as the pause lasts, where on `main` the document is open through it. Nobody is asked meanwhile, and the way to end it sooner is to cancel the run. - The request gains one field, the mark, and the approvals plugin gains a reconciler that correctness depends on, where `main` has a report. Every approval on an object that declares `closedStates` carries the mark at each decision and is reconciled, also one that holds nothing back. diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 9944d4a929d..bcaeb4fd4f9 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 42 | -| Object name statically decidable | 40 | +| Write call sites | 51 | +| Object name statically decidable | 49 | | Object name chosen at run time | 2 | -| Object name spelled inline | 38 | +| Object name spelled inline | 47 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 40 | +| Against a tenancy-enabled object | 49 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 42 | +| Threading a tenant context | 51 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 40 | +| Threading a decidably elevated (`isSystem`) context | 49 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 42 | +| Receiver carried a readable engine type | 51 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -50,11 +50,11 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 17 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 20 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 10 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 16 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/packages/cli/test/lowered-body-face-enumeration.test.ts b/packages/cli/test/lowered-body-face-enumeration.test.ts index cf5d7953323..481c74bff72 100644 --- a/packages/cli/test/lowered-body-face-enumeration.test.ts +++ b/packages/cli/test/lowered-body-face-enumeration.test.ts @@ -281,11 +281,11 @@ describe('the lowered body face, against the in-process HookContext (#22837)', ( expect(body.get('session')).toBe('passthrough'); // [#25905] Carried member by member, so a member the spec adds to it later is seen as absent. expect(inProcess.get('provenance')).toEqual(new Set([ - 'flowRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', + 'flowRunId', 'flowRootRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', 'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy', ])); expect(body.get('provenance')).toEqual(new Set([ - 'flowRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', + 'flowRunId', 'flowRootRunId', 'attributedUserId', 'performedByClientId', 'performedByAgentId', 'performedByConversationId', 'performedByConfirmationId', 'impersonatedBy', ])); // A tombstone is no member: `session.roles` is `retiredKey(…)`. diff --git a/packages/core/src/security/assemble-execution-context.test.ts b/packages/core/src/security/assemble-execution-context.test.ts index c1ba4c9ab59..c4e13e5a652 100644 --- a/packages/core/src/security/assemble-execution-context.test.ts +++ b/packages/core/src/security/assemble-execution-context.test.ts @@ -470,6 +470,7 @@ describe('#6216 — the field set is CLOSED', () => { 'transaction', 'traceId', 'flowRunId', + 'flowRootRunId', 'skipTriggers', 'skipAutomations', 'seedReplay', diff --git a/packages/core/src/security/assemble-execution-context.ts b/packages/core/src/security/assemble-execution-context.ts index 7d79757889a..bd7fc7bbb3f 100644 --- a/packages/core/src/security/assemble-execution-context.ts +++ b/packages/core/src/security/assemble-execution-context.ts @@ -91,7 +91,7 @@ import type { ResolvedAuthzContext } from './resolve-authz-context.js'; * hook layer (ADR-0014 D2, #4586), never by identity resolution. * - `rlsMembership` — engine-side RLS scoping cache. * - `transaction` / `traceId` — per-operation handles. - * - `flowRunId`, `skipTriggers`, `skipAutomations`, `seedReplay`, + * - `flowRunId`, `flowRootRunId`, `skipTriggers`, `skipAutomations`, `seedReplay`, * `skipStateMachine`, `preserveAudit`, `keptOptionValues` — per-write * behaviour flags, server-constructed at the call site (`keptOptionValues` * by the import runner, from the cells one import kept). @@ -106,6 +106,7 @@ type NonEntryExecutionContextField = | 'transaction' | 'traceId' | 'flowRunId' + | 'flowRootRunId' | 'skipTriggers' | 'skipAutomations' | 'seedReplay' diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index 797ad896683..33f22156b5f 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -59,6 +59,7 @@ import { FLOW_TRIGGER_READINESS_USER_TEXT } from './validate-flow-trigger-readin import { FLOW_TEMPLATE_PATHS_USER_TEXT } from './validate-flow-template-paths.user-text.js'; import { FLOW_NODE_WRITES_USER_TEXT } from './validate-flow-node-writes.user-text.js'; import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; +import { APPROVAL_CLOSED_STATES_USER_TEXT } from './validate-approval-closed-states.user-text.js'; import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; import { FLOW_PATTERNS_USER_TEXT } from './lint-flow-patterns.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; @@ -181,6 +182,7 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( FLOW_TEMPLATE_PATHS_USER_TEXT, FLOW_NODE_WRITES_USER_TEXT, READONLY_FLOW_WRITES_USER_TEXT, + APPROVAL_CLOSED_STATES_USER_TEXT, FLOW_CREDENTIAL_LITERALS_USER_TEXT, FLOW_PATTERNS_USER_TEXT, // The dashboard writes: widget and chart binding advisories. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 155de88eaa3..38204a5eb04 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -214,6 +214,13 @@ export type { ReadonlyFlowWriteSeverity, } from './validate-readonly-flow-writes.js'; +export { + validateApprovalClosedStates, + approvalRootObjectsOf, + APPROVAL_CLOSED_STATE_GAP, +} from './validate-approval-closed-states.js'; +export type { ApprovalClosedStateFinding } from './validate-approval-closed-states.js'; + export { validateReadonlyHookWrites, HOOK_API_UPDATE_READONLY_FIELD, diff --git a/packages/lint/src/reference-integrity-suite.test.ts b/packages/lint/src/reference-integrity-suite.test.ts index 1f9660673a7..5f009f8b504 100644 --- a/packages/lint/src/reference-integrity-suite.test.ts +++ b/packages/lint/src/reference-integrity-suite.test.ts @@ -92,6 +92,9 @@ describe('reference-integrity suite — membership', () => { // resolves the same flow's CRUD write maps against that object. 'validateNotifyEmailFieldRecipients', 'validateReadonlyFlowWrites', + // [ADR-0162 D5, #37766] The approval opening conditions at authoring, + // the same two writes and the same subject as the member above. + 'validateApprovalClosedStates', // [#13653] The hook-side half of the readonly write judgement: a body's // `ctx.api` update to a declared-`readonly` field, placed beside the flow // twin that asks the identical question one surface over. diff --git a/packages/lint/src/reference-integrity-suite.ts b/packages/lint/src/reference-integrity-suite.ts index f2e397375de..d336ca71427 100644 --- a/packages/lint/src/reference-integrity-suite.ts +++ b/packages/lint/src/reference-integrity-suite.ts @@ -133,6 +133,7 @@ import { validateActionBodyWrites } from './validate-action-body-writes.js'; import { validateFlowNodeWrites } from './validate-flow-node-writes.js'; import { validateNotifyEmailFieldRecipients } from './validate-notify-email-field-recipients.js'; import { validateReadonlyFlowWrites } from './validate-readonly-flow-writes.js'; +import { validateApprovalClosedStates } from './validate-approval-closed-states.js'; import { validateReadonlyHookWrites } from './validate-readonly-hook-writes.js'; import { validateReadonlyActionWrites } from './validate-readonly-action-writes.js'; import { validateReactPageProps } from './validate-react-page-props.js'; @@ -850,6 +851,21 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [ subjects: ['flows'], run: validateReadonlyFlowWrites, }, + // [ADR-0162 D5, Execution item 7; #37766 N45, maintainer ruling 7253749311, + // option D] An approval that could not show itself in progress on a field its + // object closes on is refused at authoring, at every door, by the one judge + // the approval's first request also asks (`@objectstack/metadata-core`, + // `approval-opening.ts`). The same two writes as the member above, for the + // same two reasons: a `flow` write judges the written flow against the live + // objects; an `object` write that starts to close on an approval's field + // judges the written package's live flows, carried as subjects, and the + // differential charges it only with the gaps it adds. + { + name: 'validateApprovalClosedStates', + runtimeTypes: ['flow', 'object'], + subjects: ['flows'], + run: validateApprovalClosedStates, + }, // [commit 36d287803] The SAME question as the member above, on the surface that had no // answer for it: a hook body's `ctx.api.object('x').update({ readonlyField })`. // A hook's `ctx.api` is a ScopedContext over the TRIGGERING operation's diff --git a/packages/lint/src/runtime-gate.approval-closed-states.test.ts b/packages/lint/src/runtime-gate.approval-closed-states.test.ts new file mode 100644 index 00000000000..84c8332d1e3 --- /dev/null +++ b/packages/lint/src/runtime-gate.approval-closed-states.test.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] + * `validateApprovalClosedStates` at the runtime publish door (Studio, REST + * `/meta`, MCP), through the real gate: a `flow` write judges the written + * flow against the live objects, its callees not in the snapshot are not + * refused; an `object` write that starts to close on an approval's field + * judges the written package's live flows (the subject pass), and a gap the + * stored universe already holds is not charged to it. The rule over whole + * stacks (the three CLI commands) is pinned in + * `validate-approval-closed-states.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +type AnyRec = Record; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const statusField = { type: 'select', label: 'Status', options: STATUSES.map((value) => ({ value, label: value })) }; + +/** As stored: no closed state. */ +const deal = (over: AnyRec = {}): AnyRec => ({ name: 'crm_deal', label: 'Deal', fields: { name: { type: 'text', label: 'Name' }, status: statusField }, ...over }); +const closingDeal = () => deal({ closedStates: { status: ['approved', 'rejected'] } }); + +const node = (id: string, type: string, config: AnyRec = {}): AnyRec => ({ id, type, label: id, config }); +const step = (id: string) => node(id, 'approval', { approvers: [{ type: 'user', value: 'u1' }], approvalStatusField: 'status' }); + +/** Two steps on the deal's approval field, with a timer between them where `hold`. */ +function approvalFlow(name: string, hold: boolean, extra: AnyRec[] = []): AnyRec { + const nodes = [ + node('start', 'start', { objectName: 'crm_deal', triggerType: 'record-after-update' }), + ...extra, + step('first'), + ...(hold ? [{ id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }] : []), + step('second'), + node('end', 'end'), + ]; + const ids = nodes.map((n) => n.id as string); + return { + name, label: name, type: 'autolaunched', nodes, + edges: ids.slice(1).map((target, i) => ({ id: `e${i}`, source: ids[i], target, ...(ids[i] === 'first' || ids[i] === 'second' ? { label: 'approve' } : {}) })), + }; +} + +const gaps = (fs: readonly F[]): F[] => fs.filter((f) => f.rule === 'approval-closed-state-gap'); + +describe('[#37766 N45] the opening conditions at the runtime publish door', () => { + it('refuses a flow write whose approval holds a pause between two steps on a closing field', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [closingDeal()] } }); + expect(result.rulesRun).toContain('validateReferenceIntegrity'); + expect(gaps(result.errors)).toEqual([expect.objectContaining({ + severity: 'error', + // The written flow is the snapshot's only flow; a carried subject is keyed by its name (below). + path: 'flows[0]', + message: 'Node hold (wait) of flow deal_wait can pause the run between two approval steps of crm_deal; move it before the first step or after the last.', + })]); + }); + + it('lets a flow write through that meets every condition', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_ok', false), context: { objects: [closingDeal()] } }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not refuse a flow write on an object that declares no closed state', () => { + const result = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [deal()] } }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not refuse a flow write for a callee the snapshot does not hold, and judges the rest', () => { + const call = node('call', 'subflow', { flowName: 'not_in_view' }); + const clean = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_call', false, [call]), context: { objects: [closingDeal()] } }); + expect(gaps([...clean.errors, ...clean.advisories])).toEqual([]); + const held = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_call', true, [call]), context: { objects: [closingDeal()] } }); + expect(gaps(held.errors)).toHaveLength(1); + }); + + it('refuses an object write that starts to close on the field of a live flow\'s approval that pauses between two steps', () => { + const result = runRuntimeAuthoringRules({ + type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [approvalFlow('deal_wait', true)] }, + }); + expect(gaps(result.errors)).toEqual([expect.objectContaining({ severity: 'error', path: 'flows.deal_wait' })]); + }); + + it('lets an object write through where the live flows meet every condition', () => { + const result = runRuntimeAuthoringRules({ + type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [approvalFlow('deal_ok', false)] }, + }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('does not charge an unrelated object write with a gap the stored universe already holds', () => { + const relabelled = { ...closingDeal(), label: 'Opportunity' }; + const result = runRuntimeAuthoringRules({ + type: 'object', item: relabelled, context: { objects: [closingDeal()], flows: [approvalFlow('deal_wait', true)] }, + }); + expect(gaps([...result.errors, ...result.advisories])).toEqual([]); + }); + + it('judges a package publish in two halves: the object write without the flow the batch redrafts, and that flow at its own write against the batch\'s object', () => { + // In a package publish the door leaves a live flow the batch redrafts out + // of an object write's subjects (`objectWriteFlowSubjects`) and judges the + // draft at its own write, against the batch's objects. The real batch is + // pinned on the kernel in plugin-approvals' + // `approval-closed-states-37766.integration.test.ts`. + const objectHalf = runRuntimeAuthoringRules({ type: 'object', item: closingDeal(), context: { objects: [deal()], flows: [] } }); + expect(gaps([...objectHalf.errors, ...objectHalf.advisories])).toEqual([]); + const repaired = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', false), context: { objects: [closingDeal()] } }); + expect(gaps([...repaired.errors, ...repaired.advisories])).toEqual([]); + const unrepaired = runRuntimeAuthoringRules({ type: 'flow', item: approvalFlow('deal_wait', true), context: { objects: [closingDeal()] } }); + expect(gaps(unrepaired.errors)).toHaveLength(1); + }); +}); diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index b91b3e9ab2c..631cfa77a37 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -336,6 +336,12 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // the shipped corpus, 0 findings; its pins live in // `runtime-gate.object-readonly-flow-writes.test.ts`. 'validateReadonlyFlowWrites', + // [ADR-0162 D5] The eighth, the same kind as the seventh: the written + // package's live flows as judged subjects, the opening conditions of an + // approval on a field the object closes on. No shipped object declares + // `closedStates`, so it reads nothing over the shipped corpus (0 + // findings); its pins live in `runtime-gate.approval-closed-states.test.ts`. + 'validateApprovalClosedStates', ]); // Every crossed member still judges flow snapshots — the #4463 P1 surface // is not narrowed by the member axis existing. diff --git a/packages/lint/src/validate-approval-closed-states.test.ts b/packages/lint/src/validate-approval-closed-states.test.ts new file mode 100644 index 00000000000..dc89ea2f9cf --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.test.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] + * `validateApprovalClosedStates` over stacks: what it refuses, through the one + * judge (`judgeApprovalOpeningSync`), and what an authoring door does not have + * in view and so does not refuse: a flow the stack does not hold, a node type + * the spec does not ship, the host's job service, an object that declares no + * `closedStates`. The door half is pinned in `runtime-gate.approval-closed-states.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { findingUserMessage } from './finding-user-text.js'; +import { APPROVAL_CLOSED_STATE_GAP, approvalRootObjectsOf, validateApprovalClosedStates } from './validate-approval-closed-states.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const statusField = (values: string[] = STATUSES) => ({ type: 'select', options: values.map((value) => ({ value, label: value })) }); + +/** Closes on its approval's outcome, and meets every condition of D5. */ +const deal = (over: Record = {}) => + ({ name: 'deal', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField(), stage: statusField(['open', 'won']) }, ...over }); + +const node = (id: string, type: string, config: Record = {}) => ({ id, type, config }); +const step = (id: string) => node(id, 'approval', { approvalStatusField: 'status' }); + +/** A flow whose nodes run one after another, starting on `object`'s records. */ +function flow(name: string, object: string | null, ...nodes: ReturnType[]) { + const all = [node('start', 'start', object ? { objectName: object } : {}), ...nodes, node('end', 'end')]; + return { name, nodes: all, edges: all.slice(1).map((b, i) => ({ id: `e${i}`, source: all[i]!.id, target: b.id })) }; +} + +const kinds = (stack: Record) => validateApprovalClosedStates(stack).map((f) => f.userTextParams.kind); + +describe('validateApprovalClosedStates: what it refuses', () => { + it('refuses a pause between two approval steps on a closing field, at error, located on the flow', () => { + const findings = validateApprovalClosedStates({ + objects: [deal()], + flows: [flow('ok', 'deal', step('a1'), step('a2')), flow('held', 'deal', step('a1'), node('w', 'wait'), step('a2'))], + }); + expect(findings).toEqual([expect.objectContaining({ + severity: 'error', rule: APPROVAL_CLOSED_STATE_GAP, where: 'flow "held"', path: 'flows[1]', + message: 'Node w (wait) of flow held can pause the run between two approval steps of deal; move it before the first step or after the last.', + userTextParams: { kind: 'pause_between_steps', flow: 'held', node: 'w', type: 'wait', object: 'deal' }, + })]); + }); + + it('refuses each field condition of D5', () => { + const noPending = deal({ fields: { status: statusField(['draft', 'approved', 'rejected']) } }); + expect(kinds({ objects: [noPending], flows: [flow('f', 'deal', step('a1'))] })).toEqual(['no_pending_option']); + const inFlight = deal({ closedStates: { status: ['pending', 'approved'] } }); + expect(kinds({ objects: [inFlight], flows: [flow('f', 'deal', step('a1'))] })).toContain('closes_in_flight'); + const readonlyWhen = deal({ fields: { status: { ...statusField(), readonlyWhen: 'true' } } }); + expect(kinds({ objects: [readonlyWhen], flows: [flow('f', 'deal', step('a1'))] })).toEqual(['readonly_when']); + }); + + it('refuses a step that mirrors onto another field than the one the object closes on', () => { + const other = flow('f', 'deal', step('a1'), node('a2', 'approval', { approvalStatusField: 'stage' })); + expect(kinds({ objects: [deal()], flows: [other] })).toContain('other_field'); + }); + + it('judges a subflow in the stack through its caller, on the caller\'s record', () => { + const child = { name: 'child', nodes: [node('s', 'start'), step('c1'), node('w', 'wait'), step('c2'), node('e', 'end')], edges: [ + { id: 'x1', source: 's', target: 'c1' }, { id: 'x2', source: 'c1', target: 'w' }, { id: 'x3', source: 'w', target: 'c2' }, { id: 'x4', source: 'c2', target: 'e' }, + ] }; + const parent = flow('parent', 'deal', node('call', 'subflow', { flowName: 'child' })); + const findings = validateApprovalClosedStates({ objects: [deal()], flows: [parent, child] }); + expect(findings.map((f) => [f.where, f.path, f.userTextParams.kind])).toEqual([['flow "child"', 'flows[1]', 'pause_between_steps']]); + }); + + it('judges a flow whose start input is a record of a closing object (#29425)', () => { + const f = { ...flow('f', null, step('a1'), node('w', 'wait'), step('a2')), variables: [{ name: 'rec', isInput: true, objectName: 'deal' }] }; + expect(kinds({ objects: [deal()], flows: [f] })).toEqual(['pause_between_steps']); + }); + + it('reads a record input as a root only where the flow declares no start object', () => { + // A run's object is a fact of how it was started; the first request judges on it alone. + const beside = { ...flow('f', 'invoice', step('a1'), node('w', 'wait'), step('a2')), variables: [{ name: 'po', isInput: true, objectName: 'deal' }] }; + expect(validateApprovalClosedStates({ objects: [deal(), { name: 'invoice', fields: {} }], flows: [beside] })).toEqual([]); + expect(approvalRootObjectsOf(beside)).toEqual(['invoice']); + }); + + it('judges a flow that declares no object on no object, leaving it to the first request', () => { + const bare = flow('f', null, step('a1'), node('w', 'wait'), step('a2')); + expect(approvalRootObjectsOf(bare)).toEqual([]); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [bare] })).toEqual([]); + }); + + it('reports a gap once, however many roots reach it', () => { + const child = flow('child', null, step('c1'), node('w', 'wait'), step('c2')); + const p1 = flow('p1', 'deal', node('call', 'subflow', { flowName: 'child' })); + const p2 = flow('p2', 'deal', node('call', 'subflow', { flowName: 'child' })); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [p1, p2, child] })).toHaveLength(1); + }); + + it('lets through an approval that meets every condition', () => { + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('ok', 'deal', step('a1'), node('d', 'decision'), step('a2'))] })).toEqual([]); + }); +}); + +describe('validateApprovalClosedStates: what an authoring door does not refuse', () => { + it('does not refuse a call to a flow the stack does not hold, and judges the rest', () => { + const f = flow('f', 'deal', node('call', 'subflow', { flowName: 'elsewhere' }), step('a1'), node('w', 'wait'), step('a2')); + expect(kinds({ objects: [deal()], flows: [f] })).toEqual(['pause_between_steps']); + const clean = flow('g', 'deal', node('call', 'subflow', { flowName: 'elsewhere' }), step('a1')); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [clean] })).toEqual([]); + }); + + it('does not refuse a node type the spec does not ship, between two steps; the spec\'s pausing types are refused', () => { + const plugin = flow('f', 'deal', step('a1'), node('p', 'acme_pausing_step'), step('a2')); + expect(validateApprovalClosedStates({ objects: [deal()], flows: [plugin] })).toEqual([]); + const screen = flow('g', 'deal', step('a1'), node('s', 'screen'), step('a2')); + expect(kinds({ objects: [deal()], flows: [screen] })).toEqual(['pause_between_steps']); + }); + + it('does not judge the host: no job service is not refused', () => { + // The judge reports `no_job_service` only where the host runs none; the rule always reads the host as running one. + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('ok', 'deal', step('a1'))] })).toEqual([]); + }); + + it('reads nothing in a stack where no object declares closedStates', () => { + const open = { name: 'deal', fields: { status: statusField(['draft', 'approved']) } }; + expect(validateApprovalClosedStates({ objects: [open], flows: [flow('f', 'deal', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); + + it('does not refuse a flow on an object the stack does not hold', () => { + expect(validateApprovalClosedStates({ objects: [deal()], flows: [flow('f', 'invoice', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); + + it('does not refuse an object that closes on another field than the approval\'s', () => { + const stageCloser = deal({ closedStates: { stage: ['won'] } }); + expect(validateApprovalClosedStates({ objects: [stageCloser], flows: [flow('f', 'deal', step('a1'), node('w', 'wait'), step('a2'))] })).toEqual([]); + }); +}); + +describe('validateApprovalClosedStates: the user sentence', () => { + it('is the first request\'s sentence for the gap, in the author\'s locale', () => { + const [finding] = validateApprovalClosedStates({ objects: [deal()], flows: [flow('held', 'deal', step('a1'), node('w', 'wait'), step('a2'))] }); + expect(findingUserMessage(finding!, ['en'])).toBe(finding!.message); + expect(findingUserMessage(finding!, ['zh-Hans'])).toContain('held'); + expect(findingUserMessage(finding!, ['zh-Hans'])).not.toBe(finding!.message); + }); +}); diff --git a/packages/lint/src/validate-approval-closed-states.ts b/packages/lint/src/validate-approval-closed-states.ts new file mode 100644 index 00000000000..275a1b7b46b --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.ts @@ -0,0 +1,191 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, maintainer ruling 7253749311, + * option D] An approval that could not show itself in progress on a field its + * object closes on is refused where it is authored, at every authoring door. + * + * The rule is the refusal at the approval's first request + * (`@objectstack/plugin-approvals`): only that request has every part of the + * approval in hand. This member reports the same conditions earlier, wherever + * the parts are in view together, and refuses the author: `os validate`, + * `os build` and `os lint` on a project's stack, and the runtime publish door + * (Studio, REST `/meta`, MCP) on a `flow` or an `object` write. The judgement + * is the one judge both doors ask, `judgeApprovalOpeningSync` + * (`@objectstack/metadata-core`, `approval-opening.ts`), so the author and the + * first request read the same verdict and the same sentences. + * + * Each flow of the stack is judged as the root of an approval, on the object + * of the record its run is started on, with the flows it calls read from the + * same stack. A run's object is a fact of how it was started, which the first + * request reads off the run; at authoring it is read off the definition: the + * `start` node's `objectName` where the flow declares one, and only where it + * declares none, the object of each start input that is a record + * (`variables[].objectName` with `isInput`, #29425), each read as a record the + * flow can be started on. A flow another one calls is judged through its caller + * as well, so a gap that only shows from the caller is reported there. + * + * What a door does not have in view is not refused here, each a reading + * pinned by a test: + * + * - **A flow not in the stack.** A `subflow` or a `map` that names a flow the + * stack does not hold is not refused (`unreadable_flow` is dropped). At the + * runtime door a `flow` write's snapshot holds the written flow alone, so a + * gap that shows only across the written flow and a flow it calls, or one + * that calls it, is refused by the CLI over the whole stack and at the + * first request, not at that write; #35143's gate owns a call to a flow the + * deployment does not hold. + * - **A node type the spec does not ship.** The pause condition is judged for + * the spec's pausing types (`FLOW_PAUSE_CAPABLE_NODE_TYPES`); any other + * type, a plugin's included, counts as one that does not pause. The first + * request reads the engine's descriptors and judges it. + * - **The host.** Whether the host runs a `job` service is a fact of the + * deployment, not of what is authored (`no_job_service` is not judged). + * - **A flow that declares no object** (no `start` object and no record + * input), started by an action or by name on a record: it is judged with no + * object for the run's record here (an object a `map` names for its items + * is still read), and the first request judges it on the run's record. + * - **An object the stack does not hold**, or one that declares no + * `closedStates`: nothing is read for it. + * + * On an `object` write the runtime door carries the written package's live + * flows as judged subjects (`subjects: ['flows']`), as it does for + * `validateReadonlyFlowWrites`, and its differential charges the write only + * with what it adds: a gap the stored universe already holds is not this + * write's. In a package publish each draft is judged against the batch's + * objects, and a live flow the batch redrafts is judged as its draft, at its + * own write (`objectWriteFlowSubjects` leaves it out of an object write's + * subjects), so a package that declares `closedStates` and repairs its flow in + * one publish passes, and one that leaves the live flow as it is is refused. + */ + +import { + judgeApprovalOpeningSync, + type OpeningCheckSource, + type OpeningFlowBody, + type OpeningGap, +} from '@objectstack/metadata-core'; +import { FLOW_PAUSE_CAPABLE_NODE_TYPES } from '@objectstack/spec/automation'; +import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; + +type AnyRec = Record; + +/** The one rule id: a condition of ADR-0162 D5 an approval in the stack does not meet. */ +export const APPROVAL_CLOSED_STATE_GAP = 'approval-closed-state-gap'; + +export interface ApprovalClosedStateFinding { + severity: 'error'; + rule: string; + /** e.g. `flow "deal_approval"`. */ + where: string; + /** e.g. `flows[2]`, the flow the gap is in. */ + path: string; + message: string; + hint: string; + /** The gap's `kind` and its names (flow, step, node, object, field, value, …), for the user sentence. */ + userTextParams: UserTextParams; +} + +/** The gap kinds an authoring door does not judge (see the module header). */ +const NOT_AT_AUTHORING: ReadonlySet = new Set(['unreadable_flow', 'no_job_service']); + +const PAUSING: ReadonlySet = new Set(FLOW_PAUSE_CAPABLE_NODE_TYPES); + +/** The developer-facing sentence of each gap kind (the first request's `en` sentence). */ +const MESSAGE: Readonly, (g: AnyRec) => string>> = { + no_pending_option: (g) => `Field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) does not declare the value pending; add it to the field's options.`, + closes_in_flight: (g) => `${g.object} closes on ${g.value} of field ${g.field} (step ${g.step} of flow ${g.flow}), a status of an approval in progress; remove ${g.value} from the object's closedStates.`, + state_machine_no_pending: (g) => `The state_machine rule ${g.rule} on field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) declares the moves out of ${g.value} without pending; add pending to them.`, + readonly_when: (g) => `Field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) carries a readonlyWhen; remove it.`, + option_visible_when: (g) => `The option ${g.value} of field ${g.field} of ${g.object} (step ${g.step} of flow ${g.flow}) carries a visibleWhen; remove it.`, + other_field: (g) => `Step ${g.step} of flow ${g.flow} can act on ${g.object} but mirrors onto field ${g.other}; every step that can act on ${g.object} must mirror onto ${g.field}.`, + no_field: (g) => `Step ${g.step} of flow ${g.flow} can act on ${g.object} but names no approval status field; every step that can act on ${g.object} must mirror onto ${g.field}.`, + pause_between_steps: (g) => `Node ${g.node} (${g.type}) of flow ${g.flow} can pause the run between two approval steps of ${g.object}; move it before the first step or after the last.`, + map_with_approval: (g) => `The map node ${g.node} of flow ${g.flow} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold ${g.object} between two steps.`, +}; + +const HINT = + 'An approval on an object that declares closedStates must be able to show itself in progress on the field the ' + + 'object closes on (ADR-0162 D5): fix the flow or the object as the sentence says. The approval\'s first request ' + + 'judges the same conditions on the record its run is started on.'; + +/** + * The objects a flow's run can be started on a record of, read off its + * definition: its `start` node's `objectName` where it declares one; only + * where it declares none, the object of each start input that is a record + * (`variables[].objectName` with `isInput`, #29425). A record input beside a + * declared start object is a record the run reads, not the run's own: the + * first request judges on the run's object alone. + */ +export function approvalRootObjectsOf(flow: AnyRec): string[] { + const out = new Set(); + for (const node of recordsOf(flow.nodes)) { + if (node.type !== 'start') continue; + const object = (node.config as AnyRec | undefined)?.objectName; + if (typeof object === 'string' && object) out.add(object); + } + if (out.size > 0) return [...out].sort(); + for (const v of recordsOf(flow.variables)) { + if (v.isInput === true && typeof v.objectName === 'string' && v.objectName) out.add(v.objectName); + } + return [...out].sort(); +} + +/** Judge every approval the stack holds whole enough to judge (see the module header). */ +export function validateApprovalClosedStates(stack: AnyRec): ApprovalClosedStateFinding[] { + const objects = recordsOf(stack.objects); + const byObject = new Map(); + for (const o of objects) if (typeof o.name === 'string') byObject.set(o.name, o); + // Nothing is read in a stack where no object declares the key. + if (![...byObject.values()].some((o) => o.closedStates != null)) return []; + + const flows = recordsOf(stack.flows); + const flowIndex = new Map(); + flows.forEach((f, i) => { if (typeof f.name === 'string' && !flowIndex.has(f.name)) flowIndex.set(f.name, i); }); + const bodyOf = (f: AnyRec): OpeningFlowBody => f as unknown as OpeningFlowBody; + + const source: OpeningCheckSource = { + objectSchema: (name) => byObject.get(name), + calleeFlow: (name) => { + const i = flowIndex.get(name); + return i === undefined ? null : { key: name, body: bodyOf(flows[i]!) }; + }, + nodeDescriptor: (type) => ({ supportsPause: PAUSING.has(type) }), + hostRunsReconciler: true, + }; + + const findings: ApprovalClosedStateFinding[] = []; + const seen = new Set(); + flows.forEach((flow, i) => { + const name = typeof flow.name === 'string' ? flow.name : `#${i}`; + const roots = approvalRootObjectsOf(flow); + for (const rootObject of roots.length > 0 ? roots : [null]) { + const judgement = judgeApprovalOpeningSync( + { rootFlow: { key: name, body: bodyOf(flow) }, rootFlowName: name, rootObject }, + source, + ); + for (const gap of judgement.gaps) { + if (NOT_AT_AUTHORING.has(gap.kind)) continue; + const key = JSON.stringify(gap); + if (seen.has(key)) continue; + seen.add(key); + const g = gap as unknown as AnyRec; + const at = typeof g.flow === 'string' ? g.flow : name; + const index = flowIndex.get(at) ?? i; + const params: Record = {}; + for (const [k, v] of Object.entries(g)) if (typeof v === 'string') params[k] = v; + findings.push({ + severity: 'error', + rule: APPROVAL_CLOSED_STATE_GAP, + where: `flow "${at}"`, + path: `flows[${index}]`, + message: MESSAGE[gap.kind as keyof typeof MESSAGE](g), + hint: HINT, + userTextParams: params, + }); + } + } + }); + return findings; +} diff --git a/packages/lint/src/validate-approval-closed-states.user-text.ts b/packages/lint/src/validate-approval-closed-states.user-text.ts new file mode 100644 index 00000000000..8411bb2784f --- /dev/null +++ b/packages/lint/src/validate-approval-closed-states.user-text.ts @@ -0,0 +1,183 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `validate-approval-closed-states.ts`'s + * `approval-closed-state-gap` findings, in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it. + * + * Who reads these: the person who published a flow or an object in Studio, or + * an AI author reading its draft's verdict, in their own language. Each + * sentence is the one an approval's first request is refused with for the + * same gap (`@objectstack/plugin-approvals`, `translations/messages.ts`, the + * `approvalOpening*` keys), so the author is told at publish exactly what the + * submitter would have been told later. The two catalogs hold the same words; + * the judge behind them is one (`@objectstack/metadata-core`, + * `approval-opening.ts`). + * + * The entry reads the finding's `userTextParams`: `kind` (the gap kind, one + * of the nine below) and the names that kind carries (`flow`, `step`, `node`, + * `type`, `object`, `field`, `value`, `rule`, `other`). + */ + +import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; +import { APPROVAL_CLOSED_STATE_GAP } from './validate-approval-closed-states.js'; + +type Kind = + | 'no_pending_option' + | 'closes_in_flight' + | 'state_machine_no_pending' + | 'readonly_when' + | 'option_visible_when' + | 'other_field' + | 'no_field' + | 'pause_between_steps' + | 'map_with_approval'; + +/** Each gap kind's sentence per locale, with `{{name}}` holes for the finding's params. */ +const SENTENCES: Readonly>>> = { + en: { + no_pending_option: "Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field's options.", + closes_in_flight: "{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object's closedStates.", + state_machine_no_pending: "The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.", + readonly_when: "Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a readonlyWhen; remove it.", + option_visible_when: "The option {{value}} of field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a visibleWhen; remove it.", + other_field: "Step {{step}} of flow {{flow}} can act on {{object}} but mirrors onto field {{other}}; every step that can act on {{object}} must mirror onto {{field}}.", + no_field: "Step {{step}} of flow {{flow}} can act on {{object}} but names no approval status field; every step that can act on {{object}} must mirror onto {{field}}.", + pause_between_steps: "Node {{node}} ({{type}}) of flow {{flow}} can pause the run between two approval steps of {{object}}; move it before the first step or after the last.", + map_with_approval: "The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.", + }, + 'zh-Hans': { + no_pending_option: "{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。", + closes_in_flight: "{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。", + state_machine_no_pending: "{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。", + readonly_when: "{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})带有 readonlyWhen;请去掉它。", + option_visible_when: "{{object}} 字段 {{field}} 的选项 {{value}}(流程 {{flow}} 的步骤 {{step}})带有 visibleWhen;请去掉它。", + other_field: "流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却把状态写到字段 {{other}};凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。", + no_field: "流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却没有指定审批状态字段;凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。", + pause_between_steps: "流程 {{flow}} 的节点 {{node}}({{type}})可能在 {{object}} 的两个审批步骤之间暂停运行;请把它移到第一步之前或最后一步之后。", + map_with_approval: "流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。", + }, + 'zh-Hant': { + no_pending_option: "{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。", + closes_in_flight: "{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。", + state_machine_no_pending: "{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。", + readonly_when: "{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})帶有 readonlyWhen;請移除它。", + option_visible_when: "{{object}} 欄位 {{field}} 的選項 {{value}}(流程 {{flow}} 的步驟 {{step}})帶有 visibleWhen;請移除它。", + other_field: "流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻把狀態寫到欄位 {{other}};凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。", + no_field: "流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻沒有指定核准狀態欄位;凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。", + pause_between_steps: "流程 {{flow}} 的節點 {{node}}({{type}})可能在 {{object}} 的兩個核准步驟之間暫停執行;請把它移到第一步之前或最後一步之後。", + map_with_approval: "流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。", + }, + es: { + no_pending_option: "El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.", + closes_in_flight: "{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.", + state_machine_no_pending: "La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.", + readonly_when: "El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un readonlyWhen; quítelo.", + option_visible_when: "La opción {{value}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un visibleWhen; quítelo.", + other_field: "El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero escribe en el campo {{other}}; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.", + no_field: "El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero no nombra ningún campo de estado de aprobación; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.", + pause_between_steps: "El nodo {{node}} ({{type}}) del flujo {{flow}} puede pausar la ejecución entre dos pasos de aprobación de {{object}}; muévalo antes del primer paso o después del último.", + map_with_approval: "El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.", + }, + ar: { + no_pending_option: "الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.", + closes_in_flight: "يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.", + state_machine_no_pending: "قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.", + readonly_when: "الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل readonlyWhen؛ أزله.", + option_visible_when: "الخيار {{value}} من الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل visibleWhen؛ أزله.", + other_field: "الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها تكتب الحالة في الحقل {{other}}؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.", + no_field: "الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها لا تسمّي حقلًا لحالة الموافقة؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.", + pause_between_steps: "العقدة {{node}} ({{type}}) في التدفق {{flow}} قد توقف التشغيل مؤقتًا بين خطوتَي موافقة على {{object}}؛ انقلها قبل الخطوة الأولى أو بعد الأخيرة.", + map_with_approval: "عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.", + }, + fr: { + no_pending_option: "Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.", + closes_in_flight: "{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d'approbation en cours ; retirez {{value}} des closedStates de l'objet.", + state_machine_no_pending: "La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.", + readonly_when: "Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un readonlyWhen ; retirez-le.", + option_visible_when: "L'option {{value}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un visibleWhen ; retirez-le.", + other_field: "L'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais écrit dans le champ {{other}} ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.", + no_field: "L'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais ne nomme aucun champ de statut d'approbation ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.", + pause_between_steps: "Le nœud {{node}} ({{type}}) du flux {{flow}} peut mettre l'exécution en pause entre deux étapes d'approbation de {{object}} ; placez-le avant la première étape ou après la dernière.", + map_with_approval: "Le nœud map {{node}} du flux {{flow}} exécute une étape d'approbation pour chaque élément, et le nœud ne montre pas qu'aucun élément n'est un enregistrement ; l'approbation d'un autre enregistrement retiendrait {{object}} entre deux étapes.", + }, + 'pt-BR': { + no_pending_option: "O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.", + closes_in_flight: "{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.", + state_machine_no_pending: "A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.", + readonly_when: "O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um readonlyWhen; remova-o.", + option_visible_when: "A opção {{value}} do campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um visibleWhen; remova-o.", + other_field: "A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas grava no campo {{other}}; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.", + no_field: "A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas não indica nenhum campo de status de aprovação; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.", + pause_between_steps: "O nó {{node}} ({{type}}) do fluxo {{flow}} pode pausar a execução entre duas etapas de aprovação de {{object}}; mova-o para antes da primeira etapa ou depois da última.", + map_with_approval: "O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.", + }, + ru: { + no_pending_option: "Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.", + closes_in_flight: "{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.", + state_machine_no_pending: "Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.", + readonly_when: "Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет readonlyWhen; уберите его.", + option_visible_when: "Вариант {{value}} поля {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет visibleWhen; уберите его.", + other_field: "Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но записывает статус в поле {{other}}; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.", + no_field: "Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но не называет поле статуса согласования; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.", + pause_between_steps: "Узел {{node}} ({{type}}) процесса {{flow}} может приостановить выполнение между двумя шагами согласования {{object}}; перенесите его до первого шага или после последнего.", + map_with_approval: "Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.", + }, + de: { + no_pending_option: "Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.", + closes_in_flight: "{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.", + state_machine_no_pending: "Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.", + readonly_when: "Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein readonlyWhen; entfernen Sie es.", + option_visible_when: "Die Option {{value}} des Feldes {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein visibleWhen; entfernen Sie es.", + other_field: "Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, schreibt aber in das Feld {{other}}; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.", + no_field: "Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, nennt aber kein Genehmigungsstatusfeld; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.", + pause_between_steps: "Der Knoten {{node}} ({{type}}) des Flows {{flow}} kann den Lauf zwischen zwei Genehmigungsschritten von {{object}} anhalten; verschieben Sie ihn vor den ersten oder hinter den letzten Schritt.", + map_with_approval: "Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.", + }, + ja: { + no_pending_option: "{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。", + closes_in_flight: "{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。", + state_machine_no_pending: "{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。", + readonly_when: "{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})に readonlyWhen があります。削除してください。", + option_visible_when: "{{object}} のフィールド {{field}} の選択肢 {{value}}(フロー {{flow}} のステップ {{step}})に visibleWhen があります。削除してください。", + other_field: "フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、フィールド {{other}} にステータスを書き込みます。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。", + no_field: "フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、承認ステータスフィールドを指定していません。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。", + pause_between_steps: "フロー {{flow}} のノード {{node}}({{type}})は {{object}} の二つの承認ステップの間で実行を一時停止する可能性があります。最初のステップの前か最後のステップの後に移動してください。", + map_with_approval: "フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。", + }, + ko: { + no_pending_option: "{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.", + closes_in_flight: "{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.", + state_machine_no_pending: "{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.", + readonly_when: "{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})에 readonlyWhen이 있습니다. 제거하세요.", + option_visible_when: "{{object}}의 필드 {{field}}의 옵션 {{value}}(흐름 {{flow}}의 단계 {{step}})에 visibleWhen이 있습니다. 제거하세요.", + other_field: "흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 필드 {{other}}에 상태를 기록합니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.", + no_field: "흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 승인 상태 필드를 지정하지 않습니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.", + pause_between_steps: "흐름 {{flow}}의 노드 {{node}}({{type}})는 {{object}}의 두 승인 단계 사이에서 실행을 일시 중지할 수 있습니다. 첫 단계 앞이나 마지막 단계 뒤로 옮기세요.", + map_with_approval: "흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.", + }, +}; + +function render(tag: string, p: UserTextParams): string { + const pack = SENTENCES[tag] ?? SENTENCES.en!; + const template = pack[p.kind as Kind] ?? SENTENCES.en![p.kind as Kind] ?? ''; + return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => p[name] ?? ''); +} + +export const APPROVAL_CLOSED_STATES_USER_TEXT: UserTextCatalog = Object.freeze({ + [APPROVAL_CLOSED_STATE_GAP]: { + en: (p) => render('en', p), + 'zh-Hans': (p) => render('zh-Hans', p), + 'zh-Hant': (p) => render('zh-Hant', p), + es: (p) => render('es', p), + ar: (p) => render('ar', p), + fr: (p) => render('fr', p), + 'pt-BR': (p) => render('pt-BR', p), + ru: (p) => render('ru', p), + de: (p) => render('de', p), + ja: (p) => render('ja', p), + ko: (p) => render('ko', p), + }, +}); diff --git a/packages/metadata-core/src/approval-opening.test.ts b/packages/metadata-core/src/approval-opening.test.ts new file mode 100644 index 00000000000..4b0eeac16ba --- /dev/null +++ b/packages/metadata-core/src/approval-opening.test.ts @@ -0,0 +1,67 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5; #37766] The one judge's two drivers agree: the first + * request's (`judgeApprovalOpening`, awaiting each read) and the authoring + * rule's (`judgeApprovalOpeningSync`, over a stack in hand). The conditions + * themselves are pinned arm by arm through the approvals plugin + * (`approval-opening-check.test.ts`) and the lint rule + * (`validate-approval-closed-states.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import { + approvalFlowWalk, + judgeApprovalOpening, + judgeApprovalOpeningSync, + type OpeningCheckSource, + type OpeningFlow, + type OpeningFlowBody, +} from './approval-opening.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; +const deal = { name: 'deal', closedStates: { status: ['approved', 'rejected'] }, fields: { status: { type: 'select', options: STATUSES.map((value) => ({ value })) } } }; + +const node = (id: string, type: string, config: Record = {}) => ({ id, type, config }); +function chain(...nodes: ReturnType[]): OpeningFlowBody { + const all = [node('start', 'start'), ...nodes, node('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} +const step = (id: string) => node(id, 'approval', { approvalStatusField: 'status' }); + +const flows: Record = { + root: chain(step('a1'), node('call', 'subflow', { flowName: 'child' }), step('a2')), + child: chain(node('w', 'wait')), +}; +const read = (name: string): OpeningFlow | null => (flows[name] ? { key: name, body: flows[name]! } : null); +const base = { + objectSchema: (name: string) => (name === 'deal' ? deal : undefined), + nodeDescriptor: (type: string) => ({ supportsPause: type === 'wait' }), + hostRunsReconciler: true, +}; +const input = { rootFlow: read('root'), rootFlowName: 'root', rootObject: 'deal' }; + +describe('the opening judge: one walk, two drivers', () => { + it('answers the same judgement over a reader that awaits and one that does not', async () => { + const sync: OpeningCheckSource = { ...base, calleeFlow: (name) => read(name) }; + const awaited: OpeningCheckSource = { ...base, calleeFlow: async (name) => read(name) }; + const a = judgeApprovalOpeningSync(input, sync); + const b = await judgeApprovalOpening(input, awaited); + expect(a).toEqual(b); + expect(a.gaps.map((g) => g.kind)).toEqual(['pause_between_steps']); + }); + + it('reads a promise handed to the synchronous driver as a flow it cannot read', () => { + const out = judgeApprovalOpeningSync(input, { ...base, calleeFlow: async (name) => read(name) }); + expect(out.gaps).toContainEqual({ kind: 'unreadable_flow', flow: 'child' }); + }); + + it('walks each callee once, and asks for each read with its caller', () => { + const asked: string[] = []; + const walk = approvalFlowWalk(read('root')!); + let step = walk.next(); + while (!step.done) { asked.push(`${step.value.callerKey}>${step.value.name}`); step = walk.next(read(step.value.name)); } + expect(asked).toEqual(['root>child']); + expect([...step.value.flows.keys()]).toEqual(['root', 'child']); + }); +}); diff --git a/packages/metadata-core/src/approval-opening.ts b/packages/metadata-core/src/approval-opening.ts new file mode 100644 index 00000000000..91d9ec8de5e --- /dev/null +++ b/packages/metadata-core/src/approval-opening.ts @@ -0,0 +1,719 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7 "The check"; #37766] The ONE judge of the + * conditions an approval opens on, wherever they are asked. + * + * Two doors ask it, and both read this module so that they cannot disagree: + * + * - **The approval's first request** (`@objectstack/plugin-approvals`, + * `ApprovalService.judgeOpening`), which reads the engine as it holds the + * approval and refuses the request. That stays the rule (ADR-0162 D5). + * - **Authoring** (`@objectstack/lint`, `validateApprovalClosedStates`, a + * member of the reference-integrity suite in the shared author-time rule + * table), which `os validate`, `os build`, `os lint` and the runtime publish + * door run on what is in view, and refuses the author (maintainer ruling + * 7253749311 on #37766, option D). + * + * Both depend on this package, which depends on `@objectstack/spec` alone, as + * `flow-cycle.ts` is shared between the engine and the authoring gate. The + * first request reads asynchronously ({@link judgeApprovalOpening}); the + * authoring rule reads a stack in hand ({@link judgeApprovalOpeningSync}). The + * two drivers walk the approval through one generator + * ({@link approvalFlowWalk}) and judge it with one function, so the verdict + * has one copy. + * + * An approval is one passage of a record through its approval flow, taken as + * a whole: the flow its root run was started on, and every flow a `subflow` + * or a `map` in it names, to any depth. This module reads that whole once and + * answers three things: + * + * 1. **Whether the approval touches an object that declares `closedStates`**: + * a step of it can act on such an object. Only then is anything stamped or + * refused. + * 2. **The set of nodes that stand between two steps** ({@link OpeningJudgement.between}), + * which each request of the approval carries from its opening, so that the + * plugin can later place a stop or a pause against it (ADR-0162 item 8, + * design note 7210179412 question 3, T2). It is stamped for every approval + * that touches such an object, also one the conditions do not concern. + * 3. **What is missing**, for every step whose mirror field the object closes + * on at a status the mirror writes for a request that is not abandoned + * (`pending`, `returned`, `approved`, `rejected`): the five conditions of + * ADR-0162 D5 as revised on 2026-11-27, the approval's unread parts, and + * the host's `job` service. + * + * Between two steps means after a step is decided, whichever way, and before + * the next step opens; the next step can be the same step opened again (a + * `map` body or a `loop` body that holds one). The read is a reachability + * over one graph of the whole approval: every node of every flow, a `subflow` + * or a `map` joined to the body it calls, every region (`loop`, `parallel`, + * `try_catch`) joined to its container. It is context-insensitive and errs one + * way only: a node that could stand between two steps on some path counts as + * standing there. A stop wrongly read as "between" costs a resubmission; the + * other error would close a document on an unfinished approval (ADR-0162 D5). + * + * Pure over a {@link OpeningCheckSource}: each door hands it the readers it + * has, and the tests hand it fixtures. + */ + +import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; + +/** The statuses the mirror writes for a request that is not abandoned. */ +const IN_APPROVAL_STATUSES = ['pending', 'returned', 'approved', 'rejected'] as const; +/** The statuses of a request whose option may carry no `visibleWhen` (D5 condition 3). */ +const REQUEST_STATUSES = ['pending', 'returned', 'approved', 'rejected', 'recalled'] as const; +/** The node types that have no executor and cannot pause (N43). */ +const STRUCTURAL_TYPES: ReadonlySet = new Set(['start', 'end']); +/** The type of an approval step. */ +const APPROVAL_TYPE = 'approval'; +/** The revise window of a returned request: not a pause between two steps (D5, ADR-0044). */ +const REVISE_WINDOW_TYPE = 'approval_revise'; +/** The two node types that call another flow; they are read by their bodies. */ +const CALL_TYPES: ReadonlySet = new Set(['subflow', 'map']); +/** How many flows one approval may name before it is read as not readable whole. */ +const MAX_FLOWS = 64; +/** How many region levels the read descends. */ +const MAX_REGION_DEPTH = 16; +/** How many `aliasOf` hops a node type's descriptor is followed. */ +const MAX_ALIAS_HOPS = 8; + +/** A flow body as the engine holds it: the parts this check reads. */ +export interface OpeningFlowBody { + nodes?: ReadonlyArray; + edges?: ReadonlyArray; +} +export interface OpeningFlowNode { + id: string; + type?: string; + label?: string; + config?: Record | null; +} +export interface OpeningFlowEdge { + source: string; + target: string; +} + +/** A flow the check read, by the key the engine files it under. */ +export interface OpeningFlow { + key: string; + body: OpeningFlowBody; +} + +/** The readers the check needs. Every one answers, never throws: the service wraps its reads. */ +export interface OpeningCheckSource { + /** The object definition registered under `name`, or `undefined`. */ + objectSchema(name: string): unknown; + /** + * The flow a `subflow` or a `map` of the flow filed under `callerKey` names + * as `name`; `null` when it cannot be read. {@link judgeApprovalOpeningSync} + * reads a promise as a flow it cannot read. + */ + calleeFlow(name: string, callerKey: string): OpeningFlow | null | Promise; + /** + * The published descriptor of a node type: `undefined` where the type + * publishes none, `'unread'` where the engine cannot be asked. + */ + nodeDescriptor(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined | 'unread'; + /** Whether the host runs the plugin's sweeps, the reconciler of ADR-0162 item 8 (a `job` service). */ + hostRunsReconciler: boolean; +} + +/** One thing that keeps the approval from opening. */ +export type OpeningGap = + | { kind: 'no_pending_option'; flow: string; step: string; object: string; field: string } + | { kind: 'closes_in_flight'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'state_machine_no_pending'; flow: string; step: string; object: string; field: string; value: string; rule: string } + | { kind: 'readonly_when'; flow: string; step: string; object: string; field: string } + | { kind: 'option_visible_when'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'other_field'; flow: string; step: string; object: string; field: string; other: string } + | { kind: 'no_field'; flow: string; step: string; object: string; field: string } + | { kind: 'pause_between_steps'; flow: string; node: string; type: string; object: string } + | { kind: 'map_with_approval'; flow: string; node: string; object: string } + | { kind: 'unreadable_flow'; flow: string } + | { kind: 'no_job_service'; object: string }; + +/** One node of the between-two-steps set: the flow it is in, by the key the engine files it under, and its id. */ +export interface BetweenNode { + flow: string; + node: string; +} + +/** What the check answers for an approval's first request. */ +export interface OpeningJudgement { + /** Whether a step of the approval can act on an object that declares `closedStates`. */ + touchesClosedStates: boolean; + /** The nodes that stand between two steps, sorted; stamped only where {@link touchesClosedStates}. */ + between: BetweenNode[]; + /** What keeps the approval from opening; empty when it opens. */ + gaps: OpeningGap[]; +} + +/** What the check is handed about the run that opens the request. */ +export interface OpeningCheckInput { + /** The flow the approval's root run was started on, read by the caller; `null` when it could not be read. */ + rootFlow: OpeningFlow | null; + /** The flow name of the root run, for a refusal that names an unread root flow. */ + rootFlowName: string; + /** The object of the root run's record; `null` for a root run that carries none (a batch). */ + rootObject: string | null; +} + +/** An object's declared closed values, field → values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ReadonlyMap> | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} + +/** A vertex of the approval's graph. A node is one vertex; a container or a call is two (its entry and its exit). */ +type Vertex = string; + +interface StepInfo { + flow: string; + node: OpeningFlowNode; + field: string | undefined; +} + +interface MapInfo { + flow: string; + node: OpeningFlowNode; + callee: string | null; + /** Whether the node shows that none of its items is a record (items written out, none of them one). */ + noRecordItems: boolean; +} + +/** One read the walk asks of its driver: the flow a call node names. */ +export interface ApprovalFlowRead { + name: string; + callerKey: string; +} + +/** What the walk of an approval's flows answers. */ +export interface ApprovalFlowWalk { + flows: Map; + calls: Map>; + gaps: OpeningGap[]; +} + +/** + * Read every flow of the approval, to any depth, from its root: a generator + * that yields each read it needs ({@link ApprovalFlowRead}) and is resumed + * with the flow read, or `null`. The two drivers below answer the reads, one + * awaiting them and one not, so the walk has one copy. + */ +export function* approvalFlowWalk(root: OpeningFlow): Generator { + const gaps: OpeningGap[] = []; + const flows = new Map(); + /** For each flow: the flows it calls, by call node, with how the call hands objects down. */ + const calls = new Map>(); + const queue: OpeningFlow[] = [root]; + flows.set(root.key, root.body); + while (queue.length > 0) { + const { key, body } = queue.shift()!; + const out: Array<{ node: OpeningFlowNode; callee: string | null; kind: 'subflow' | 'map' }> = []; + for (const node of allNodes(body)) { + if (!node.type || !CALL_TYPES.has(node.type)) continue; + const name = typeof node.config?.flowName === 'string' ? node.config.flowName : ''; + if (!name) { + gaps.push({ kind: 'unreadable_flow', flow: `${key} › ${node.id}` }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + const callee = yield { name, callerKey: key }; + if (!callee) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + out.push({ node, callee: callee.key, kind: node.type as 'subflow' | 'map' }); + if (!flows.has(callee.key)) { + if (flows.size >= MAX_FLOWS) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + continue; + } + flows.set(callee.key, callee.body); + queue.push(callee); + } + } + calls.set(key, out); + } + return { flows, calls, gaps }; +} + +/** + * Read the approval whole and judge it, awaiting each read (the first + * request). Never throws: a part that cannot be read is a gap + * ({@link OpeningGap} `unreadable_flow`), and an approval with one cannot be + * judged, so it does not open. + */ +export async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { + if (!input.rootFlow) return unreadRoot(input); + const walk = approvalFlowWalk(input.rootFlow); + let step = walk.next(); + while (!step.done) step = walk.next(await source.calleeFlow(step.value.name, step.value.callerKey)); + return judgeWalkedApproval(input, input.rootFlow, step.value, source); +} + +/** + * The same judgement over readers that answer at once (a stack in hand: the + * authoring rule). A read answered with a promise is a flow it cannot read. + */ +export function judgeApprovalOpeningSync(input: OpeningCheckInput, source: OpeningCheckSource): OpeningJudgement { + if (!input.rootFlow) return unreadRoot(input); + const walk = approvalFlowWalk(input.rootFlow); + let step = walk.next(); + while (!step.done) { + const read = source.calleeFlow(step.value.name, step.value.callerKey); + step = walk.next(read instanceof Promise ? null : read); + } + return judgeWalkedApproval(input, input.rootFlow, step.value, source); +} + +function unreadRoot(input: OpeningCheckInput): OpeningJudgement { + return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; +} + +/** Judge an approval whose flows {@link approvalFlowWalk} has read. */ +function judgeWalkedApproval( + input: OpeningCheckInput, + rootFlow: OpeningFlow, + walked: ApprovalFlowWalk, + source: OpeningCheckSource, +): OpeningJudgement { + const { flows, calls } = walked; + const gaps: OpeningGap[] = [...walked.gaps]; + + // ── 2. The objects each flow's steps can act on ─────────────────────────── + // The root flow acts on the root run's record. A `subflow` body acts on its + // caller's record. A `map` body acts on an item where the item is a record, + // on the object the node names for its items (else its caller's), and on its + // caller's record where the item is not one; the check cannot read ahead + // whether an item is a record unless the items are written out in the node. + const objects = new Map>(); + for (const key of flows.keys()) objects.set(key, new Set()); + if (input.rootObject) objects.get(rootFlow.key)!.add(input.rootObject); + const maps: MapInfo[] = []; + for (const [key, list] of calls) { + for (const call of list) { + if (call.kind === 'map') maps.push({ flow: key, node: call.node, callee: call.callee, noRecordItems: itemsShowNoRecord(call.node) }); + } + } + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + const mine = objects.get(key)!; + for (const call of list) { + if (!call.callee) continue; + const theirs = objects.get(call.callee)!; + const before = theirs.size; + if (call.kind === 'subflow') { + for (const o of mine) theirs.add(o); + } else { + const items = mapItems(call.node); + const anyRecord = items === undefined || items.some(isRecordItem); + const anyOther = items === undefined || items.some((i) => !isRecordItem(i)); + if (anyOther) for (const o of mine) theirs.add(o); + if (anyRecord) { + const itemObject = typeof call.node.config?.itemObject === 'string' && call.node.config.itemObject + ? call.node.config.itemObject : undefined; + if (itemObject) theirs.add(itemObject); + else for (const o of mine) theirs.add(o); + } + } + if (theirs.size !== before) changed = true; + } + } + } + + // ── 3. The steps, and whether the approval touches a closing object ─────── + const steps: StepInfo[] = []; + for (const [key, body] of flows) { + for (const node of allNodes(body)) { + if (node.type !== APPROVAL_TYPE) continue; + const field = typeof node.config?.approvalStatusField === 'string' && node.config.approvalStatusField + ? node.config.approvalStatusField : undefined; + steps.push({ flow: key, node, field }); + } + } + const declaring = (object: string) => closedValuesOf(source.objectSchema(object)) !== undefined; + const touchesClosedStates = gaps.length > 0 + || steps.some((s) => [...objects.get(s.flow)!].some(declaring)); + if (!touchesClosedStates) return { touchesClosedStates: false, between: [], gaps: [] }; + + // ── 4. The nodes between two steps ──────────────────────────────────────── + const graph = buildGraph(flows, calls); + const stepVertices = steps.map((s) => vertexOf(s.flow, s.node.id)); + const after = reach(graph.succ, stepVertices); + const before = reach(graph.pred, stepVertices); + const betweenKeys = new Set(); + const pausing: Array<{ flow: string; node: OpeningFlowNode }> = []; + // A node other than a step is between two steps where a step can come + // before it and a step can follow it. A step is in the set where a step can + // follow it: a run that stops on a step decided with no later step logged + // (design note question 3, T2) stopped between two steps exactly then. + for (const [vertex, owner] of graph.owner) { + if (!before.has(vertex)) continue; + const isStep = owner.node.type === APPROVAL_TYPE; + if (!isStep && !after.has(vertex)) continue; + const k = `${owner.flow}\u0000${owner.node.id}`; + if (betweenKeys.has(k)) continue; + betweenKeys.add(k); + if (!isStep && canPause(owner.node, source)) pausing.push(owner); + } + // A `map` or a `loop` whose body holds a step stands between two steps + // where it is entered before a step and left after one: between one item's + // (one pass's) step and the next, the run is parked at the node or back on + // it. A `subflow` is not: its body runs once. + for (const { flow, node } of graph.owner.values()) { + if (node.type !== 'map' && node.type !== 'loop') continue; + if (before.has(vertexOf(flow, node.id, 'in')) && after.has(vertexOf(flow, node.id, 'out'))) { + betweenKeys.add(`${flow}\u0000${node.id}`); + } + } + const between = [...betweenKeys] + .map((k) => { const [flow, node] = k.split('\u0000'); return { flow, node }; }) + .sort((a, b) => (a.flow === b.flow ? cmp(a.node, b.node) : cmp(a.flow, b.flow))); + + // ── 5. The conditions, for every step they concern ──────────────────────── + const concernedObjects = new Set(); + for (const step of steps) { + for (const object of objects.get(step.flow)!) { + const schema = source.objectSchema(object); + const closed = closedValuesOf(schema); + if (!closed || !step.field) continue; + const values = closed.get(step.field); + if (!values || !IN_APPROVAL_STATUSES.some((s) => values.has(s))) continue; + concernedObjects.add(object); + judgeField(step, object, step.field, schema, values, gaps); + // Condition 4: every step that can act on a record of the object names that field. + for (const other of steps) { + if (other === step || !objects.get(other.flow)!.has(object)) continue; + if (other.field === step.field) continue; + if (other.field) gaps.push({ kind: 'other_field', flow: other.flow, step: other.node.id, object, field: step.field, other: other.field }); + else gaps.push({ kind: 'no_field', flow: other.flow, step: other.node.id, object, field: step.field }); + } + } + } + if (concernedObjects.size > 0) { + const object = [...concernedObjects].sort(cmp)[0]; + // Condition 5: no node that can pause the run of itself stands between two steps. + for (const p of pausing) { + gaps.push({ kind: 'pause_between_steps', flow: p.flow, node: p.node.id, type: String(p.node.type ?? ''), object }); + } + // Condition 5, its second half: no `map` with an approval step in its body, + // at any depth, where the parent's object is one the conditions concern, + // unless the node shows that none of its items is a record. + const holdsStep = flowsHoldingSteps(flows, calls, steps); + for (const m of maps) { + if (!m.callee || !holdsStep.has(m.callee) || m.noRecordItems) continue; + const parentObjects = [...objects.get(m.flow)!].filter((o) => concernedObjects.has(o)).sort(cmp); + if (parentObjects.length > 0) gaps.push({ kind: 'map_with_approval', flow: m.flow, node: m.node.id, object: parentObjects[0] }); + } + } + + // ── 6. The host ─────────────────────────────────────────────────────────── + if (!source.hostRunsReconciler) { + const object = steps.flatMap((s) => [...objects.get(s.flow)!]).filter(declaring).sort(cmp)[0]; + if (object) gaps.push({ kind: 'no_job_service', object }); + } + + return { touchesClosedStates, between, gaps: dedupe(gaps) }; +} + +/** D5 conditions 1 to 3, on the field `field` of `object`, for `step`. */ +function judgeField( + step: StepInfo, object: string, field: string, schema: unknown, + closed: ReadonlySet, gaps: OpeningGap[], +): void { + const flow = step.flow; + const stepId = step.node.id; + const def = (schema as { fields?: Record } | undefined)?.fields?.[field] as + { options?: unknown; readonlyWhen?: unknown } | undefined; + const options = Array.isArray(def?.options) ? def!.options as unknown[] : []; + const optionOf = (value: string): Record | undefined => { + for (const o of options) { + if (o && typeof o === 'object' && String((o as { value?: unknown }).value) === value) return o as Record; + } + return undefined; + }; + const declares = (value: string) => options.some((o) => (o && typeof o === 'object' ? String((o as { value?: unknown }).value) : String(o)) === value); + + // 1. The field declares `pending`, and the object closes on neither `pending` nor `returned`. + if (!declares('pending')) gaps.push({ kind: 'no_pending_option', flow, step: stepId, object, field }); + for (const value of ['pending', 'returned']) { + if (closed.has(value)) gaps.push({ kind: 'closes_in_flight', flow, step: stepId, object, field, value }); + } + + // 2. A `state_machine` rule on the field that declares the moves out of a + // closed `approved` or `rejected` has `pending` among them. + const rules = (schema as { validations?: unknown } | undefined)?.validations; + if (Array.isArray(rules)) { + for (const rule of rules) { + const r = rule as { type?: unknown; field?: unknown; active?: unknown; transitions?: unknown; name?: unknown } | null; + if (!r || r.type !== 'state_machine' || r.field !== field || r.active === false) continue; + const transitions = r.transitions && typeof r.transitions === 'object' ? r.transitions as Record : {}; + for (const value of ['approved', 'rejected']) { + if (!closed.has(value) || !Object.prototype.hasOwnProperty.call(transitions, value)) continue; + const moves = transitions[value]; + if (!Array.isArray(moves) || !moves.includes('pending')) { + gaps.push({ kind: 'state_machine_no_pending', flow, step: stepId, object, field, value, rule: String(r.name ?? '') }); + } + } + } + } + + // 3. The field carries no `readonlyWhen`, and none of its options for a request's status carries a `visibleWhen`. + if (def?.readonlyWhen != null) gaps.push({ kind: 'readonly_when', flow, step: stepId, object, field }); + for (const value of REQUEST_STATUSES) { + const option = optionOf(value); + if (option && option.visibleWhen != null) gaps.push({ kind: 'option_visible_when', flow, step: stepId, object, field, value }); + } +} + +/** Whether a node can pause the run of itself, by what its type declares (D5 condition 5, N43). */ +function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { + const type = node.type; + if (!type) return true; // a node it cannot place counts as one that can + if (STRUCTURAL_TYPES.has(type) || type === APPROVAL_TYPE || type === REVISE_WINDOW_TYPE || CALL_TYPES.has(type)) return false; + let descriptor = source.nodeDescriptor(type); + for (let hop = 0; descriptor && descriptor !== 'unread' && typeof descriptor.aliasOf === 'string' && hop < MAX_ALIAS_HOPS; hop++) { + const canonical = source.nodeDescriptor(descriptor.aliasOf as string); + if (!canonical || canonical === 'unread' || canonical === descriptor) break; + descriptor = canonical; + } + if (descriptor === 'unread' || descriptor === undefined) return true; + return descriptor.supportsPause === true; +} + +/** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ +function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { + const out: OpeningFlowNode[] = []; + const visit = (nodes: ReadonlyArray | undefined, depth: number) => { + for (const node of nodes ?? []) { + if (!node || typeof node !== 'object' || typeof node.id !== 'string') continue; + out.push(node); + if (depth >= MAX_REGION_DEPTH) continue; + for (const region of regionsOf(node)) visit(region.nodes, depth + 1); + } + }; + visit(body.nodes, 0); + return out; +} + +/** The regions a container node holds, in slot order. */ +function regionsOf(node: OpeningFlowNode): Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> { + const slots = node.type ? FLOW_REGION_SLOTS_BY_TYPE.get(node.type) : undefined; + if (!slots) return []; + const out: Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> = []; + for (const slot of slots) { + const value = node.config?.[slot.key]; + const list = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : (value ? [value] : []); + list.forEach((raw, i) => { + // A `parallel` branch carries its region beside its name; read either shape. + const region = raw && typeof raw === 'object' && 'region' in (raw as object) + ? (raw as { region?: OpeningFlowBody }).region : raw as OpeningFlowBody; + if (region && typeof region === 'object') { + out.push({ slot: `${slot.key}[${i}]`, region, nodes: region.nodes, edges: region.edges }); + } + }); + } + return out; +} + +/** The items a `map` node writes out in itself, or `undefined` where they are read from an expression. */ +function mapItems(node: OpeningFlowNode): unknown[] | undefined { + const collection = node.config?.collection; + return Array.isArray(collection) ? collection : undefined; +} + +/** Whether an item is a record, read as the `map` node reads it (an object with a string `id`). */ +function isRecordItem(item: unknown): boolean { + return item != null && typeof item === 'object' && typeof (item as { id?: unknown }).id === 'string'; +} + +/** Whether a `map` node shows that none of its items is a record: its items are written out, and none is one. */ +function itemsShowNoRecord(node: OpeningFlowNode): boolean { + const items = mapItems(node); + return items !== undefined && !items.some(isRecordItem); +} + +/** The flows whose body holds an approval step at any depth, through the flows it calls. */ +function flowsHoldingSteps( + flows: Map, + calls: Map>, + steps: StepInfo[], +): Set { + const holds = new Set(steps.map((s) => s.flow)); + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + if (holds.has(key)) continue; + if (list.some((c) => c.callee && holds.has(c.callee))) { holds.add(key); changed = true; } + } + } + return holds; +} + +function vertexOf(flow: string, node: string, part = ''): Vertex { + return `${flow}\u0000${node}\u0000${part}`; +} + +interface Graph { + succ: Map>; + pred: Map>; + /** Each vertex that stands for a node, with the node and its flow. Synthetic vertices are absent. */ + owner: Map; +} + +/** + * One graph of the whole approval. A plain node is one vertex. A container + * (`loop`, `parallel`, `try_catch`) and a call (`subflow`, `map`) are two, its + * entry and its exit, joined through the regions or the body it runs: + * - a region or a called body is entered from the entry and left to the exit; + * - a `loop` body and a `map` body may run again (exit → entry) or not at all + * (entry → exit); + * - the branches of a `parallel` may interleave, so each branch's exit leads + * into every other branch; + * - every node of a `try` region may fail into its `catch` region and to the + * container's exit; + * - an edge of the flow, a `fault` edge included, leads from its source's exit + * to its target's entry. + * A step is one vertex: its decision leaves it. + */ +function buildGraph( + flows: Map, + calls: Map>, +): Graph { + const succ = new Map>(); + const pred = new Map>(); + const owner = new Map(); + const link = (a: Vertex, b: Vertex) => { + if (!succ.has(a)) succ.set(a, new Set()); + if (!pred.has(b)) pred.set(b, new Set()); + succ.get(a)!.add(b); + pred.get(b)!.add(a); + }; + const entryOfFlow = (key: string) => vertexOf(key, '', 'flow-entry'); + const exitOfFlow = (key: string) => vertexOf(key, '', 'flow-exit'); + const calleeOf = new Map(); + for (const [key, list] of calls) for (const c of list) calleeOf.set(`${key}\u0000${c.node.id}`, c); + + const isCompound = (node: OpeningFlowNode) => !!node.type && (CALL_TYPES.has(node.type) || FLOW_REGION_SLOTS_BY_TYPE.has(node.type)); + const inOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'in' : ''); + const outOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'out' : ''); + + /** Wire one graph (a flow's top level or a region); answers its entry and exit vertices. */ + const wire = (flow: string, nodes: ReadonlyArray | undefined, edges: ReadonlyArray | undefined, depth: number): + { entries: Vertex[]; exits: Vertex[]; inner: Vertex[] } => { + const list = (nodes ?? []).filter((n) => n && typeof n === 'object' && typeof n.id === 'string'); + const byId = new Map(list.map((n) => [n.id, n])); + const inner: Vertex[] = []; + const hasIn = new Set(); + const hasOut = new Set(); + for (const e of edges ?? []) { + const a = byId.get(e?.source); + const b = byId.get(e?.target); + if (!a || !b) continue; + link(outOf(flow, a), inOf(flow, b)); + hasOut.add(a.id); + hasIn.add(b.id); + } + for (const node of list) { + const vin = inOf(flow, node); + const vout = outOf(flow, node); + owner.set(vin, { flow, node }); + owner.set(vout, { flow, node }); + inner.push(vin); + if (vout !== vin) inner.push(vout); + const call = calleeOf.get(`${flow}\u0000${node.id}`); + if (call) { + if (call.callee) { + link(vin, entryOfFlow(call.callee)); + link(exitOfFlow(call.callee), vout); + if (call.kind === 'map') link(exitOfFlow(call.callee), entryOfFlow(call.callee)); + } else { + link(vin, vout); + } + if (call.kind === 'map') link(vin, vout); + continue; + } + const regions = depth < MAX_REGION_DEPTH ? regionsOf(node) : []; + if (node.type && FLOW_REGION_SLOTS_BY_TYPE.has(node.type)) { + const wired = regions.map((r) => ({ slot: r.slot, ...wire(flow, r.nodes, r.edges, depth + 1) })); + if (wired.length === 0) link(vin, vout); + if (node.type === 'try_catch') { + const tryR = wired.filter((w) => w.slot.startsWith('try')); + const catchR = wired.filter((w) => w.slot.startsWith('catch')); + for (const t of tryR) { + for (const e of t.entries) link(vin, e); + for (const x of t.exits) link(x, vout); + for (const v of t.inner) { + link(v, vout); + for (const c of catchR) for (const e of c.entries) link(v, e); + } + } + for (const c of catchR) for (const x of c.exits) link(x, vout); + } else { + for (const w of wired) { + for (const e of w.entries) link(vin, e); + for (const x of w.exits) link(x, vout); + } + if (node.type === 'loop') { + link(vin, vout); + for (const w of wired) for (const x of w.exits) for (const e of w.entries) link(x, e); + } + if (node.type === 'parallel') { + for (const a of wired) for (const b of wired) { + if (a === b) continue; + for (const x of a.exits) for (const e of b.entries) link(x, e); + } + } + } + } + } + const entries = list.filter((n) => (depth === 0 ? n.type === 'start' || !hasIn.has(n.id) : !hasIn.has(n.id))).map((n) => inOf(flow, n)); + const exits = list.filter((n) => !hasOut.has(n.id)).map((n) => outOf(flow, n)); + return { entries, exits, inner }; + }; + + for (const [key, body] of flows) { + const { entries, exits } = wire(key, body.nodes, body.edges, 0); + for (const e of entries) link(entryOfFlow(key), e); + for (const x of exits) link(x, exitOfFlow(key)); + } + return { succ, pred, owner }; +} + +/** The vertices reachable from `starts` by one edge or more. */ +function reach(edges: Map>, starts: Vertex[]): Set { + const seen = new Set(); + const stack: Vertex[] = []; + for (const s of starts) for (const n of edges.get(s) ?? []) stack.push(n); + while (stack.length > 0) { + const v = stack.pop()!; + if (seen.has(v)) continue; + seen.add(v); + for (const n of edges.get(v) ?? []) if (!seen.has(n)) stack.push(n); + } + return seen; +} + +function cmp(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function dedupe(gaps: OpeningGap[]): OpeningGap[] { + const seen = new Set(); + return gaps.filter((g) => { + const k = JSON.stringify(g); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); +} diff --git a/packages/metadata-core/src/index.ts b/packages/metadata-core/src/index.ts index 7ff5e75a786..1ca977714e1 100644 --- a/packages/metadata-core/src/index.ts +++ b/packages/metadata-core/src/index.ts @@ -158,6 +158,11 @@ export * from './extension-field-patch-targets.js'; // engine refuses to register no longer reads valid and publishes. export * from './flow-cycle.js'; +// [ADR-0162 D5, #37766] The ONE judge of the conditions an approval opens on: +// the approvals plugin asks it at an approval's first request, and the lint +// rule `validateApprovalClosedStates` asks it at every authoring door. +export * from './approval-opening.js'; + // [epic cloud#3652 Q3] The package upgrade plan — one comparison of an installed // package version with the incoming one, read by `os diff`, the marketplace // install door's dry run and the `manifest` service's `planUpgrade`, so the diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index 6ffb26988fe..de4d9418da1 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -485,6 +485,22 @@ describe('[ADR-0106 D1] references to a denied field — inside a READABLE field expect(served.uiReadonlyWhen).toBe("record.title != ''"); }); + // [ADR-0162 D1] The closed states are keyed by this object's fields. + it('[ADR-0162] drops a `closedStates` entry keyed by the denied field, and keeps the readable one', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { secret_score: ['high'], title: ['done'] } }); + expect(served.closedStates).toEqual({ title: ['done'] }); + }); + + it('[ADR-0162] deletes `closedStates` when its only entry is keyed by the denied field', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { secret_score: ['high'] } }); + expect('closedStates' in served).toBe(false); + }); + + it('[ADR-0162] CONTROL: a closing VALUE spelled like the denied field is a literal, served as written', () => { + const served = mask({ name: 'thing', fields: fieldsWith(), closedStates: { title: ['secret_score'] } }); + expect(served.closedStates).toEqual({ title: ['secret_score'] }); + }); + it('drops a `lookupAutofill` pair whose target is denied, and keeps a source named on the referenced object', () => { // #27945 — `target` is a field of THIS object; `source` names a field of // the lookup's `reference` object, which this projection cannot judge. diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 082a2298ee0..4efb8515321 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -854,6 +854,13 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { // Expressions. titleFormat: expression, uiReadonlyWhen: objectHandLock, + // [ADR-0162 D1] The closed states: KEYED by a field of this object, each + // value a list of that field's option codes (literals, never a field + // reference). An entry whose key is a denied field goes — the field does + // not exist for that caller, nor do the states it closes on — and an + // emptied map is deleted. The engine judges the stored declaration + // whoever is served what; this is the served document only. + closedStates: recordOf(keep, true), // Rule entries — dropped whole when they mention a denied field. validations: ruleEntries, indexes: ruleEntries, diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 26ab331ba26..13f5483241b 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -416,13 +416,15 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // from (ADR-0160 D8), which gives its MCP prompt a record argument. // [#37402] `object` 52 → 53: `uiReadonlyWhen`, the whole-record hand lock // (no person edits a field of the record at the console; writes keep it). - // [#37792] `object` 53 → 54: `pinOverview`, the record page layout switch + // [ADR-0162 D1] `object` 53 → 54: `closedStates`, the states in which a + // record and its master-detail lines are closed to change. + // [#37792] `object` 54 → 55: `pinOverview`, the record page layout switch // (ADR-0085's Note of 2026-11-27). - // [#37802] `object` 54 → 55: `fieldTabs`, the record page's field tabs + // [#37802] `object` 55 → 56: `fieldTabs`, the record page's field tabs // (the same Note). const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 89, flow: 24, - hook: 24, object: 55, page: 28, position: 14, report: 24, skill: 18, tool: 14, + hook: 24, object: 56, page: 28, position: 14, report: 24, skill: 18, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( diff --git a/packages/objectql/src/closed-state-lock.ts b/packages/objectql/src/closed-state-lock.ts new file mode 100644 index 00000000000..ce3bf64287d --- /dev/null +++ b/packages/objectql/src/closed-state-lock.ts @@ -0,0 +1,921 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D2 to D7, D10] The closed-state lock: the engine's judgement of a + * write that reaches a CLOSED record, or a line of one. + * + * ## What is closed (D2) + * + * An object declares `closedStates` (`packages/spec/src/data/object.zod.ts`): + * a map from one of its single-value `select` fields to the values of it that + * close a record. A record is closed when, for at least one named field, the + * STORED value is one of the listed ones. Nothing is stored for it: every + * judgement below reads the row as the store holds it when the write reaches + * it, inside the write's own unit of work (the driver options each read is + * given carry the open transaction). + * + * ## The unit (D3) + * + * The record and every row that points at it through a `master_detail` field, + * one level deep. A line under two masters is a line of both. Lookups and + * satellite objects are not in the unit. {@link closedStateUnitOf} reads it off + * the registry; an object that neither declares the key nor is a line of one + * that does answers `undefined`, and its writes read nothing extra (D10). + * + * ## Who is bound (D5) + * + * Every write not made in a system context, a write with no context at all + * included ({@link boundByClosedStates}). No grant opens a closed record, and + * the state field is frozen with the rest. + * + * ## What is refused (D4) + * + * | Write | closed record | line of a closed record | + * |---|---|---| + * | create | not judged | refused | + * | update | refused | refused | + * | delete | refused | refused | + * | move a line | — | refused when either end is closed | + * + * An update is judged by the keys it carries: one with no key writes nothing + * and is not refused. A many-row write is refused whole before any row is + * written. Three cases cannot be judged and are refused: + * - a predicate write on a store that cannot run the line probe, whose + * matched rows pass the engine's per-row ceiling; + * - a line write that names its master by something that is not one id; + * - a read of the state that fails. + * + * ## Where it runs (D10) + * + * In the engine's write path, inside the executor the middleware chain calls, + * so after the object-permission and row-access gates have answered, and + * before the before-phase hooks. A master the write NAMES is consulted only + * when the caller's own read door returns it (otherwise the reference gate + * refuses the write in its own words, later). A master the stored row already + * hangs under is judged on its stored state, whoever the writer is: that read + * is the engine's, above the writer's grants and inside its organization scope. + * + * ## The refusal (D8) + * + * `409 RECORD_LOCKED`, the code the pending-approval lock already answers + * with. What a person reads is the Operation Message Catalog's sentence + * (`@objectstack/spec/system`), in the caller's language, carried as the + * error's `userMessage` and as its `message` behind the code, the shape the + * pending lock's refusal has, so the wire's `error` reads the same sentence + * ({@link closedStateRefusalSentence}): + * + * - a record's own write: `record_closed*`, naming the record by its + * object's label and the title the WRITER would be served under its own + * field permissions ({@link servedTitleOf}); ⛔ never the title as stored; + * - a write that matched rows by a predicate: the label form, no title; + * - a line write, a line's restore: the label form, naming the MASTER (the + * engine reads the master's state to judge, and reads nothing of it to word + * the refusal); + * - a delete refused for what it would also remove: + * `record_closed_delete_blocked*`, naming the record asked to be deleted + * and the label of the object in the way, the title only where the caller + * is served one and the delete names exactly one record by id. + * + * The title is named only from a field that holds display text and that the + * writer's generic read returns: never a field the generic read withholds + * (`internal`, or a credential type: `secret-fields.ts`), a reference field, + * or a field the object's `closedStates` names ({@link titleFieldOf}). + * + * No form carries a record id, an API name or the state's value. The + * developer's sentence, which names objects by their API names, is carried on + * `developerMessage`, which no person-facing surface reads and the data door + * does not relay. A refusal that could not judge the write (D4's three cases) + * keeps the developer's sentence as its `message` and marks no `userMessage`: + * it is addressed to whoever scoped the write, as the pending lock's + * unanswerable-bound refusal is. + */ + +import { MAX_BULK_PER_ROW_HOOK_ROWS, REFERENCE_VALUE_TYPES, ReadableIds, resolveDisplayField, type FilterCondition } from '@objectstack/spec/data'; +import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { ISecurityService } from '@objectstack/spec/contracts'; +import { renderOperationMessage } from '@objectstack/spec/system'; +import { objectDisplayLabel } from './engine-validation-messages.js'; +import { SECURITY_SERVICE_SOURCE_SLOT } from './engine-top-level.js'; +import type { ValidationMessageContext } from './validation/record-validator.js'; +import { isDriverTenantScopedSchema } from './engine-driver-options.js'; +import { isFederatedObject } from './federated-object.js'; +import { driverCompilesReadableIdsLeaf } from './relation-semi-join.js'; +import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; +import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; + +export { closedValuesOf, type ClosedValues }; + +/** The code every closed-state refusal carries. */ +export const CLOSED_STATE_LOCK_CODE = 'RECORD_LOCKED'; + +/** A `master_detail` edge from a line object to a master that declares closed states. */ +export interface ClosedMasterEdge { + /** The line's foreign-key column. */ + readonly fk: string; + /** The master object's resolved name. */ + readonly master: string; + /** The master's closed values. */ + readonly closed: ClosedValues; +} + +/** What the lock reads off the registry for one object. */ +export interface ClosedStateUnit { + /** The object's own closed values, when it declares the key. */ + readonly own: ClosedValues | undefined; + /** Every `master_detail` edge to a master that declares the key. */ + readonly masters: readonly ClosedMasterEdge[]; +} + +/** The engine members the lock reads. */ +export interface ClosedStateLockHost { + readonly _registry: { getObject(name: string): unknown }; + resolveObjectName(name: string): string; + getDriver(object: string): any; + buildDriverOptions(object: string, context: ExecutionContext | undefined, base?: any, extra?: any): any; + masterDetailHeadersCallerReads(master: string, ids: ReadonlyArray, context: ExecutionContext | undefined): Promise>; + resolveEnginePosture(): TenancyPosture; + /** + * [D8] The caller's locale and translator, which the refusal's sentence and + * the labels it names are worded in (`engine-validation-messages.ts`). + * Absent: English and the declared labels. + */ + validationMessageContext?(object: string, context?: { locale?: string }): ValidationMessageContext; + /** + * [D8] The engine, whose security-service source slot answers which fields + * the writer is served ({@link servedTitleOf}). Absent: no title is named. + */ + readonly facade?: object; + /** [D8] Where a title read that failed on the refusal path is reported. */ + readonly logger?: { warn(message: string, meta?: Record): void }; +} + +/** The verbs a refusal names. */ +export type ClosedStateWriteVerb = 'update' | 'delete' | 'create' | 'restore'; + +/** Why a write was refused. */ +export type ClosedStateRefusalReason = + /** The record itself is closed. */ + | 'record_closed' + /** The row is a line of a closed record (or moves into or out of one). */ + | 'master_closed' + /** A delete's cascade reaches a closed record or a line of one. */ + | 'cascade_reaches_closed' + /** The write could not be judged (D4's three cases). */ + | 'cannot_judge'; + +/** The refusal every closed-state judgement throws. */ +export interface ClosedStateLockError extends Error { + readonly code: typeof CLOSED_STATE_LOCK_CODE; + readonly status: 409; + readonly statusCode: 409; + /** The object the write was made on. */ + readonly object: string; + readonly reason: ClosedStateRefusalReason; + /** For `master_closed` and `cascade_reaches_closed`: the object whose closed record stands in the way. */ + readonly blockingObject?: string; + /** What the lock read: `closed_state`, the one lock read's reason (ADR-0162 D9). */ + readonly lockReason: 'closed_state'; + /** [D8] The catalog's sentence, in the caller's locale. Absent on a refusal that could not judge the write. */ + readonly userMessage?: string; + /** [D8] The developer's sentence (API names), where `message` carries the person's. */ + readonly developerMessage?: string; +} + +/** + * Build the refusal. `message` is the developer's: it names objects by their + * API names and never a record id or a state value. + */ +export function closedStateLockError( + object: string, + verb: ClosedStateWriteVerb, + reason: ClosedStateRefusalReason, + blockingObject?: string, + detail?: string, +): ClosedStateLockError { + const what = reason === 'record_closed' + ? `the '${object}' record is closed (its object declares closedStates and the record is in one of them), so it cannot be ${verbPast(verb)}` + : reason === 'master_closed' + ? `the '${object}' row is a line of a closed '${blockingObject}' record, so it cannot be ${verbPast(verb)}` + : reason === 'cascade_reaches_closed' + ? `deleting this '${object}' record would also remove a closed '${blockingObject}' record or a line of one; nothing was deleted` + : `the closed-state lock could not judge this ${verb} on '${object}'${detail ? `: ${detail}` : ''}; it is refused rather than taken for open`; + const err = new Error(`${CLOSED_STATE_LOCK_CODE}: ${what}.`) as Error & Record; + err.name = 'ClosedStateLockError'; + err.code = CLOSED_STATE_LOCK_CODE; + err.status = 409; + err.statusCode = 409; + err.object = object; + err.reason = reason; + if (blockingObject !== undefined) err.blockingObject = blockingObject; + err.lockReason = 'closed_state'; + return err as unknown as ClosedStateLockError; +} + +function verbPast(verb: ClosedStateWriteVerb): string { + switch (verb) { + case 'update': return 'changed'; + case 'delete': return 'deleted'; + case 'create': return 'added'; + case 'restore': return 'restored under it'; + } +} + +// ── The sentence a person reads (D8) ───────────────────────────────────────── + +/** The host members the sentence is worded from. */ +type WordingHost = Pick; + +/** What a refusal names, by the case it answers. */ +export type ClosedStateRefusalWording = + /** A record's own write. `row` is the record as stored; absent for a write that matched rows by a predicate. */ + | { readonly kind: 'record'; readonly object: string; readonly row?: Record } + /** A line write, or a line's restore: the master, by its label alone. */ + | { readonly kind: 'master'; readonly master: string } + /** A delete refused for what it would also remove: the record asked to be deleted, and the object in the way. */ + | { readonly kind: 'delete_blocked'; readonly object: string; readonly row?: Record; readonly blockingObject: string }; + +function messagesFor(host: WordingHost, object: string, context: ExecutionContext | undefined): ValidationMessageContext | undefined { + try { + return host.validationMessageContext?.(object, context); + } catch { + // A misbehaving i18n service words the refusal in English; it never turns a 409 into a 500. + return undefined; + } +} + +/** + * The object's label in the caller's locale: the translation, else the + * declared label. `undefined` when it has neither: the API name, the last + * rung of `objectDisplayLabel`, never reaches this sentence. + */ +function objectLabelOf(host: WordingHost, object: string, messages: ValidationMessageContext | undefined): string | undefined { + let declared: string | undefined; + try { + const raw = (host._registry.getObject(object) as { label?: unknown } | undefined)?.label; + declared = typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined; + } catch { + declared = undefined; + } + let label: string; + try { + label = objectDisplayLabel(object, declared, messages ?? {}); + } catch { + label = declared ?? object; + } + return label && !(label === object && declared === undefined) ? label : undefined; +} + +/** + * The field an object's title is read from (ADR-0079's one arbiter), or + * `undefined`. A title is named only from a field whose value is display + * text and that the generic read returns, so the arbiter's answer gives no + * title when it is: + * - the id; + * - a field the generic read withholds: `internal` + * (`collectInternalReadFields`, left out of every row `engine-find.ts` + * returns) or a credential type (`collectCredentialFields`, served masked + * in those rows); `engine-find.ts`'s search scan skips the union of the + * two; + * - a reference field (`REFERENCE_VALUE_TYPES`): its value is a record id; + * - a field the object's `closedStates` names: its value is an option code. + */ +function titleFieldOf(host: Pick, object: string): string | undefined { + try { + const schema = host._registry.getObject(object) as { fields?: Record } | undefined; + const field = resolveDisplayField(schema as never); + if (!field || field === 'id' || field === '_id') return undefined; + if (collectInternalReadFields(schema as never).includes(field)) return undefined; + if (collectCredentialFields(schema as never).includes(field)) return undefined; + const type = schema?.fields?.[field]?.type; + if (typeof type === 'string' && REFERENCE_VALUE_TYPES.has(type)) return undefined; + if (closedValuesOf(schema)?.has(field)) return undefined; + return field; + } catch { + return undefined; + } +} + +/** + * [D8] The engine slot `ObjectQLPlugin` fills, beside + * `SECURITY_SERVICE_SOURCE_SLOT`, with a probe answering whether a `security` + * service is registered at all, read without building one (`false`: nothing + * is registered under the name). Read only by {@link titleFieldIsServed}, and + * only when the security source throws; no other reader of the source slot + * consults it. Not public surface. + */ +export const SECURITY_SERVICE_REGISTERED_SLOT: unique symbol = Symbol.for('objectstack.objectql.securityServiceRegistered'); + +/** + * [D8] True only when the host's registration probe answers that no + * `security` service is registered. A missing probe, a probe that throws, and + * any answer but `false` mean a service may be registered: no title. + */ +async function noSecurityServiceRegistered(facade: unknown): Promise { + const probe = (facade as Record)[SECURITY_SERVICE_REGISTERED_SLOT]; + if (typeof probe !== 'function') return false; + try { + return (await probe()) === false; + } catch { + return false; + } +} + +/** + * [D8] May the writer be served `field` of `object`? The rule the pending lock + * picks its title by (`plugin-approvals` `resolveReadableSnapshotFields`): the + * field is readable for the writer AND not served masked to it (the security + * contract's `getQueryableFields` is the read projection minus the masked + * fields), asked of the registered `security` service with the writer's own + * execution context. + * + * With no security service registered (the slot empty, or its source + * answering `null` or nothing) there is no field-level security: a read serves + * every field, so the stored title is the served one. So it is when the + * source throws and the host's registration probe + * (`SECURITY_SERVICE_REGISTERED_SLOT`) answers that no `security` service is + * registered: the in-repo kernels throw on a name nothing registered. Every + * other answer short of a clear yes names no title: a host that lends no + * engine, a slot that holds no function, a source that throws for a service + * that is registered (or with no probe to say it is not), a service without + * either member, a question that throws or answers nothing. + */ +async function titleFieldIsServed(host: WordingHost, object: string, field: string, context: ExecutionContext | undefined): Promise { + if (!host.facade) return false; + // Read from the engine slot at use (see SECURITY_SERVICE_SOURCE_SLOT), never cached. + const source = (host.facade as Record)[SECURITY_SERVICE_SOURCE_SLOT]; + if (source === undefined || source === null) return true; + if (typeof source !== 'function') return false; + let svc: Partial> | null | undefined; + try { + svc = source() as typeof svc; + } catch { + // A source that throws names no title, unless the host's registration + // probe answers that no `security` service is registered at all. + return noSecurityServiceRegistered(host.facade); + } + if (svc === undefined || svc === null) return true; + if (typeof svc.getReadableFields !== 'function' || typeof svc.getQueryableFields !== 'function') return false; + try { + const readable = await svc.getReadableFields(object, context as never); + if (!Array.isArray(readable) || !readable.includes(field)) return false; + const unmasked = await svc.getQueryableFields(object, context as never); + return Array.isArray(unmasked) && unmasked.includes(field); + } catch { + return false; + } +} + +/** + * [D8] The record's title as the writer would be served it, or `undefined`. + * Read off `row`, the record as stored (the engine's own read), and named only + * when the writer may be served the title field ({@link titleFieldIsServed}). + * An empty title, or one whose value is the record's id, is no title. + */ +export async function servedTitleOf( + this: WordingHost, + object: string, + row: Record | null | undefined, + context: ExecutionContext | undefined, +): Promise { + if (!row || typeof row !== 'object') return undefined; + const field = titleFieldOf(this, object); + if (!field) return undefined; + const raw = row[field]; + if (raw === null || raw === undefined || typeof raw === 'object') return undefined; + const title = String(raw).trim(); + if (!title) return undefined; + const id = row.id ?? row._id; + if (id !== undefined && id !== null && title === String(id)) return undefined; + return (await titleFieldIsServed(this, object, field, context)) ? title : undefined; +} + +/** + * [D8] The sentence a person reads for a closed-state refusal, rendered from + * the Operation Message Catalog in the caller's locale. Which form applies + * picks the KEY; the labels and the title are its parameters. + */ +export async function closedStateRefusalSentence( + this: WordingHost, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const subject = wording.kind === 'master' ? wording.master : wording.object; + const messages = messagesFor(this, subject, context); + const render = (messageKey: string, params: Record = {}) => + renderOperationMessage({ messageKey, params }, { locale: messages?.locale, translate: messages?.translate }); + try { + if (wording.kind === 'master') { + const label = objectLabelOf(this, wording.master, messages); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const label = objectLabelOf(this, wording.object, messages); + const title = await servedTitleOf.call(this, wording.object, wording.row, context); + if (wording.kind === 'record') { + if (title) return label ? render('record_closed', { object: label, title }) : render('record_closed_unlabeled', { title }); + return label ? render('record_closed_untitled', { object: label }) : render('record_closed_opaque'); + } + const blocking = objectLabelOf(this, wording.blockingObject, messages); + if (!label || !blocking) return render('record_closed_delete_blocked_opaque'); + return title + ? render('record_closed_delete_blocked', { object: label, title, blockingObject: blocking }) + : render('record_closed_delete_blocked_untitled', { object: label, blockingObject: blocking }); + } catch { + return render(wording.kind === 'delete_blocked' ? 'record_closed_delete_blocked_opaque' : 'record_closed_opaque'); + } +} + +/** + * [D8] The refusal as a person reads it: `err`'s developer sentence is carried + * on `developerMessage`, and the catalog's sentence becomes its `userMessage` and + * its `message` (behind the code, which the data door strips). + */ +async function sayClosed( + this: WordingHost, + err: ClosedStateLockError, + wording: ClosedStateRefusalWording, + context: ExecutionContext | undefined, +): Promise { + const sentence = await closedStateRefusalSentence.call(this, wording, context); + const e = err as unknown as Record; + e.developerMessage = err.message; + e.message = `${CLOSED_STATE_LOCK_CODE}: ${sentence}`; + e.userMessage = sentence; + return err; +} + +/** + * [D5] Is a write in `context` bound by the lock? Every write is, except one + * made in a system context. A write with no context is bound: no identity is + * not an elevated identity. + */ +export function boundByClosedStates(context: ExecutionContext | undefined): boolean { + return context?.isSystem !== true; +} + +/** + * [D3, D10] What the lock reads for `object`: its own closed values and its + * `master_detail` edges to masters that declare them. `undefined` when there + * is neither, which is the "free when not declared" answer: the write reads + * nothing extra. + */ +export function closedStateUnitOf(this: Pick, object: string): ClosedStateUnit | undefined { + const schema = this._registry.getObject(object) as { fields?: Record } | undefined; + if (!schema) return undefined; + const own = closedValuesOf(schema); + const masters: ClosedMasterEdge[] = []; + for (const [name, def] of Object.entries(schema.fields ?? {})) { + if (!def || def.type !== 'master_detail') continue; + const ref = typeof def.reference === 'string' && def.reference ? def.reference : undefined; + if (!ref) continue; + let master: string; + try { master = this.resolveObjectName(ref); } catch { master = ref; } + const closed = closedValuesOf(this._registry.getObject(master)); + if (!closed) continue; + masters.push({ fk: typeof def.name === 'string' && def.name ? def.name : name, master, closed }); + } + if (!own && masters.length === 0) return undefined; + return { own, masters }; +} + +/** Is `row` closed under `closed`? An empty state value closes nothing. */ +export function rowIsClosed(row: Record | null | undefined, closed: ClosedValues): boolean { + if (!row) return false; + for (const [field, values] of closed) { + const v = row[field]; + if (typeof v === 'string' && v !== '' && values.has(v)) return true; + } + return false; +} + +/** The closed predicate over an object's own stored columns. */ +export function closedPredicate(closed: ClosedValues): FilterCondition { + const legs = [...closed].map(([field, values]) => ({ [field]: { $in: [...values] } }) as FilterCondition); + return legs.length === 1 ? legs[0]! : ({ $or: legs } as FilterCondition); +} + +/** A scalar id, or `null` for an empty value; `undefined` for a value that names something but not as one id. */ +function scalarIdOf(value: unknown): string | null | undefined { + if (value === undefined || value === null || value === '') return null; + if (typeof value === 'string') return value; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return undefined; +} + +const IN_CHUNK = 500; + +function chunks(list: readonly T[], size = IN_CHUNK): T[][] { + const out: T[][] = []; + for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)); + return out; +} + +/** + * Does any of `ids` of `master` stand in a closed state? Asked of the store, + * not listed: one existence probe per chunk of ids, the closed predicate in + * its `where` (D4). Read by the engine itself: straight from the store, above + * the writer's grants, inside the writer's organization scope and unit of work + * (the driver options of `context`). A read that fails is refused as "cannot + * be judged". + */ +async function anyClosedAmong( + this: Pick, + master: string, + ids: ReadonlyArray, + closed: ClosedValues, + context: ExecutionContext | undefined, + refuse: (detail: string) => Error, +): Promise { + const unique = [...new Set(ids)]; + if (unique.length === 0) return false; + try { + const driver = this.getDriver(master); + const opts = this.buildDriverOptions(master, context); + for (const part of chunks(unique)) { + const rows = (await driver.find( + master, + { object: master, where: andWhere(idIn(part), closedPredicate(closed)), fields: ['id'], limit: 1 }, + opts, + )) as unknown[] | null; + if (Array.isArray(rows) && rows.length > 0) return true; + } + } catch (error) { + throw Object.assign(refuse(`the state of a '${master}' record could not be read`), { cause: error }); + } + return false; +} + +function idIn(part: ReadonlyArray): FilterCondition { + return { id: part.length === 1 ? part[0] : { $in: [...part] } } as FilterCondition; +} + +/** + * The named-master judgement (D10): for each id the write names as the master + * of a line, the caller's read door first; the state only of a master the door + * returns. A master it does not return is not this lock's to answer. + */ +async function namedMastersClosed( + this: ClosedStateLockHost, + edge: ClosedMasterEdge, + named: ReadonlyArray, + context: ExecutionContext | undefined, + refuse: (detail: string) => Error, +): Promise { + if (named.length === 0) return false; + const readable = await this.masterDetailHeadersCallerReads(edge.master, named, context); + const asked = named.filter((id) => readable.has(id)); + if (asked.length === 0) return false; + return anyClosedAmong.call(this, edge.master, asked, edge.closed, context, refuse); +} + +/** The keys an update carries, addressing excluded. */ +function carriedKeys(payload: Record | null | undefined): string[] { + if (!payload || typeof payload !== 'object') return []; + return Object.keys(payload).filter((k) => k !== 'id'); +} + +/** [D7] The referential clear the engine wrote, and nothing else beside it. */ +export interface ClosedStateReferentialClear { + readonly field: string; + readonly value: unknown; +} + +function isBareReferentialClear(payload: Record | null | undefined, clear: ClosedStateReferentialClear | undefined): boolean { + if (!clear || !payload) return false; + const keys = carriedKeys(payload); + return keys.length === 1 && keys[0] === clear.field && Object.is(payload[clear.field], clear.value); +} + +/** Input of {@link judgeClosedStateByIdWrite}. */ +export interface ClosedStateByIdWrite { + readonly object: string; + readonly verb: 'update' | 'delete'; + /** The stored row, as the write's own prior read returned it. */ + readonly prior: Record; + /** An update's payload as the caller (and the middleware chain) left it, before the before-phase hooks. */ + readonly payload?: Record | null; + readonly context: ExecutionContext | undefined; + /** An update that is the engine's referential clear or the recycle bin's re-link (D7). */ + readonly referentialClear?: ClosedStateReferentialClear; +} + +/** + * [D4, D6, D7, D10] Judge a by-id update or delete. Called after the write's + * prior read (the row as stored, inside the write's unit of work) and before + * the before-phase hooks. + */ +export async function judgeClosedStateByIdWrite(this: ClosedStateLockHost, write: ClosedStateByIdWrite): Promise { + const { object, verb, prior, payload, context } = write; + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit) return; + if (verb === 'update') { + if (carriedKeys(payload).length === 0) return; + if (isBareReferentialClear(payload, write.referentialClear)) return; + } + if (unit.own && rowIsClosed(prior, unit.own)) { + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object, row: prior }, context); + } + const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); + for (const edge of unit.masters) { + // The master the stored row hangs under: its stored state, whoever writes. + const stored = scalarIdOf(prior[edge.fk]); + if (stored === undefined) throw refuse(`its '${edge.fk}' does not hold one id`); + if (stored !== null && await anyClosedAmong.call(this, edge.master, [stored], edge.closed, context, refuse)) { + throw await masterClosed(edge.master); + } + // A move names the master it moves to: the caller's read door first. + if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { + const named = scalarIdOf(payload[edge.fk]); + if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (named !== null && named !== stored && await namedMastersClosed.call(this, edge, [named], context, refuse)) { + throw await masterClosed(edge.master); + } + } + } +} + +/** + * [D4] Judge a create (one row or many) of lines of a master that declares + * closed states. A create of a record is not judged: there is no stored state + * yet. Refused whole when one row names a closed master the caller may read. + */ +export async function judgeClosedStateCreate( + this: ClosedStateLockHost, + object: string, + rows: ReadonlyArray | null | undefined>, + context: ExecutionContext | undefined, +): Promise { + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit || unit.masters.length === 0) return; + const refuse = (detail: string) => closedStateLockError(object, 'create', 'cannot_judge', undefined, detail); + for (const edge of unit.masters) { + const named: string[] = []; + for (const row of rows) { + if (!row || typeof row !== 'object') continue; + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (id !== null) named.push(id); + } + if (await namedMastersClosed.call(this, edge, [...new Set(named)], context, refuse)) { + throw await sayClosed.call(this, closedStateLockError(object, 'create', 'master_closed', edge.master), { kind: 'master', master: edge.master }, context); + } + } +} + +/** Input of {@link judgeClosedStatePredicateWrite}. */ +export interface ClosedStatePredicateWrite { + readonly object: string; + readonly verb: 'update' | 'delete'; + /** The write's AST as the middleware chain composed it: the caller's row scope is in its `where`. */ + readonly ast: { where?: unknown }; + /** The driver options the write's own matched-row read is given. */ + readonly driverOptions: unknown; + readonly payload?: Record | null; + readonly context: ExecutionContext | undefined; + /** The write's one read of its matched rows (a memo), for a store that cannot run the line probe. */ + readonly readMatchedRows: () => Promise> | null>; +} + +/** + * Can one statement on `object`'s store answer "does a matched row hang under + * a closed `master`"? The line and the master share a driver that compiles the + * composed `ReadableIds` semi-join leaf, the master is not federated, and under + * a walled posture both are of the same tenancy class (so one read's driver + * options scope both tables). + */ +function lineProbeServes(this: Pick, object: string, master: string): boolean { + const driver = this.getDriver(object); + if (!driverCompilesReadableIdsLeaf(driver)) return false; + if (this.getDriver(master) !== driver) return false; + const masterSchema = this._registry.getObject(master); + if (isFederatedObject(masterSchema)) return false; + if (postureEnforcesWall(this.resolveEnginePosture()) && + isDriverTenantScopedSchema(this._registry.getObject(object) as never) !== isDriverTenantScopedSchema(masterSchema as never)) return false; + return true; +} + +function andWhere(where: unknown, extra: FilterCondition): FilterCondition { + if (where === undefined || where === null) return extra; + if (typeof where === 'object' && !Array.isArray(where) && Object.keys(where as object).length === 0) return extra; + return { $and: [where as FilterCondition, extra] } as FilterCondition; +} + +/** + * [D4] Judge a predicate update or delete, whole, before any row is written. + * + * - The record's own state: one existence probe, the write's own composed + * predicate joined to the closed predicate. + * - A line's masters: one probe through a semi-join to the master where the + * store can run it ({@link lineProbeServes}); otherwise the write's one read + * of its matched rows, under the engine's per-row ceiling, and one read of + * the masters those rows hang under. A set over the ceiling cannot be + * judged and is refused. + * - An update that moves every matched line to a named master: that master, + * through the caller's read door first. + */ +export async function judgeClosedStatePredicateWrite(this: ClosedStateLockHost, write: ClosedStatePredicateWrite): Promise { + const { object, verb, ast, payload, context } = write; + if (!boundByClosedStates(context)) return; + const unit = closedStateUnitOf.call(this, object); + if (!unit) return; + if (verb === 'update' && carriedKeys(payload).length === 0) return; + const refuse = (detail: string) => closedStateLockError(object, verb, 'cannot_judge', undefined, detail); + const driver = this.getDriver(object); + const probe = async (where: FilterCondition): Promise => { + try { + const rows = (await driver.find(object, { object, where, fields: ['id'], limit: 1 }, write.driverOptions)) as unknown[] | null; + return Array.isArray(rows) && rows.length > 0; + } catch (error) { + throw Object.assign(refuse('the probe for a closed record failed'), { cause: error }); + } + }; + if (unit.own && await probe(andWhere(ast.where, closedPredicate(unit.own)))) { + // Matched by a predicate: no one row is named, so no title (the label form). + throw await sayClosed.call(this, closedStateLockError(object, verb, 'record_closed'), { kind: 'record', object }, context); + } + const masterClosed = (master: string) => + sayClosed.call(this, closedStateLockError(object, verb, 'master_closed', master), { kind: 'master', master }, context); + let matched: ReadonlyArray> | undefined; + const matchedRows = async (): Promise>> => { + if (matched) return matched; + let rows: ReadonlyArray> | null; + try { + rows = await write.readMatchedRows(); + } catch (error) { + throw Object.assign(refuse('the read of the rows it matches failed'), { cause: error }); + } + matched = (rows ?? []).filter((r): r is Record => r != null && typeof r === 'object'); + if (matched.length > MAX_BULK_PER_ROW_HOOK_ROWS) { + throw refuse(`its store cannot run the line probe and it matches ${matched.length} rows, over the engine's per-row ceiling of ${MAX_BULK_PER_ROW_HOOK_ROWS}`); + } + return matched; + }; + for (const edge of unit.masters) { + if (lineProbeServes.call(this, object, edge.master)) { + const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; + if (await probe(andWhere(ast.where, semiJoin))) throw await masterClosed(edge.master); + } else { + const ids: string[] = []; + for (const row of await matchedRows()) { + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`a matched row's '${edge.fk}' does not hold one id`); + if (id !== null) ids.push(id); + } + if (await anyClosedAmong.call(this, edge.master, ids, edge.closed, context, refuse)) { + throw await masterClosed(edge.master); + } + } + if (verb === 'update' && payload && Object.prototype.hasOwnProperty.call(payload, edge.fk)) { + const named = scalarIdOf(payload[edge.fk]); + if (named === undefined) throw refuse(`the master named by '${edge.fk}' is not one id`); + if (named !== null && await namedMastersClosed.call(this, edge, [named], context, refuse)) { + throw await masterClosed(edge.master); + } + } + } +} + +/** + * [D6] Judge the set a delete's cascade will remove, collected whole before + * any row is removed (`engine-cascade-planning.ts#cascadeDeleteRelations`). + * Refused whole when a member is closed, or is a line of a closed record. The + * refusal names the record the caller asked to delete and the object whose + * closed record stands in the way, and nothing else (D8): the record by its + * title as the caller is served it where `named` (the ids the delete named, + * never the set planned so far) holds exactly one, else by its object's label + * alone. A delete that names its rows by a predicate passes none. + */ +export async function judgeClosedStateCascadeSet( + this: Pick, + root: string, + members: ReadonlyMap>, + context: ExecutionContext | undefined, + named: ReadonlyArray = [], +): Promise { + if (!boundByClosedStates(context)) return; + const refuse = (detail: string) => closedStateLockError(root, 'delete', 'cannot_judge', undefined, detail); + const blocked = async (blockingObject: string) => + sayClosed.call( + this, + closedStateLockError(root, 'delete', 'cascade_reaches_closed', blockingObject), + { kind: 'delete_blocked', object: root, row: named.length === 1 ? await storedTitleRow.call(this, root, named[0]!, context) : undefined, blockingObject }, + context, + ); + for (const [object, idSet] of members) { + const unit = closedStateUnitOf.call(this, object); + if (!unit || idSet.size === 0) continue; + const parts = chunks([...idSet].map(String)); + const driver = this.getDriver(object); + const opts = this.buildDriverOptions(object, context); + // Asked of the store, per chunk of the set's ids: one existence probe. + const probe = async (part: ReadonlyArray, extra: FilterCondition): Promise => { + try { + const rows = (await driver.find(object, { object, where: andWhere(idIn(part), extra), fields: ['id'], limit: 1 }, opts)) as unknown[] | null; + return Array.isArray(rows) && rows.length > 0; + } catch (error) { + throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); + } + }; + if (unit.own) { + for (const part of parts) { + if (await probe(part, closedPredicate(unit.own))) throw await blocked(object); + } + } + for (const edge of unit.masters) { + if (lineProbeServes.call(this, object, edge.master)) { + // The predicate door's semi-join, scoped to the set's ids. + const semiJoin = { [edge.fk]: { $in: ReadableIds.compose(ReadableIds.of(edge.master), closedPredicate(edge.closed)) } } as FilterCondition; + for (const part of parts) { + if (await probe(part, semiJoin)) throw await blocked(edge.master); + } + continue; + } + // A store that cannot run the semi-join: the set's foreign keys, then + // one probe of the masters they name (D4's stated fallback). + const masterIds: string[] = []; + try { + for (const part of parts) { + const rows = (await driver.find(object, { object, where: idIn(part), fields: ['id', edge.fk], limit: part.length }, opts)) as Array> | null; + for (const row of rows ?? []) { + if (!row || typeof row !== 'object') continue; + const id = scalarIdOf(row[edge.fk]); + if (id === undefined) throw refuse(`a '${object}' row its cascade reaches does not hold one id in '${edge.fk}'`); + if (id !== null) masterIds.push(id); + } + } + } catch (error) { + if ((error as { reason?: unknown })?.reason === 'cannot_judge') throw error; + throw Object.assign(refuse(`the rows of '${object}' its cascade reaches could not be read`), { cause: error }); + } + if (await anyClosedAmong.call(this, edge.master, masterIds, edge.closed, context, refuse)) { + throw await blocked(edge.master); + } + } + } +} + +/** + * [D8] The title column of the one record a delete names, read by the engine + * from the store (inside the caller's organization scope and unit of work), so + * the refusal can name it as the caller is served it ({@link servedTitleOf}). + * Read only on the refusal path. A read that fails is reported at `warn` and + * names no title: the refusal stands whole either way, and only its wording + * falls back to the label form. + */ +async function storedTitleRow( + this: Pick, + object: string, + id: string | number, + context: ExecutionContext | undefined, +): Promise | undefined> { + const field = titleFieldOf(this, object); + if (!field) return undefined; + try { + const rows = (await this.getDriver(object).find( + object, + { object, where: { id }, fields: ['id', field], limit: 1 }, + this.buildDriverOptions(object, context), + )) as Array> | null; + return Array.isArray(rows) && rows[0] && typeof rows[0] === 'object' ? rows[0] : undefined; + } catch (error) { + this.logger?.warn( + `[closed-state] the title of the '${object}' record a refused delete names could not be read; the refusal names its object's label instead`, + { object, error: (error as Error)?.message ?? String(error) }, + ); + return undefined; + } +} + +/** + * [D7] Restore: an entry that would put a row back under a LIVE, closed master + * that is not itself part of the entry is refused before anything is written. + * `parents` lists, for each such reference, the line's object and field and + * the live master's id. + */ +export async function judgeClosedStateRestore( + this: Pick, + parents: ReadonlyArray<{ object: string; field: string; master: string; id: string }>, + context: ExecutionContext | undefined, +): Promise { + if (!boundByClosedStates(context)) return; + const byMaster = new Map(); + for (const p of parents) { + // Named as the restore's own judgement names it: the reference as declared. + const master = p.master; + const closed = closedValuesOf(this._registry.getObject(master)); + if (!closed) continue; + const slot = byMaster.get(master) ?? { closed, ids: [], object: p.object }; + slot.ids.push(p.id); + byMaster.set(master, slot); + } + for (const [master, { closed, ids, object }] of byMaster) { + const refuse = (detail: string) => closedStateLockError(object, 'restore', 'cannot_judge', undefined, detail); + if (await anyClosedAmong.call(this, master, ids, closed, context, refuse)) { + throw await sayClosed.call(this, closedStateLockError(object, 'restore', 'master_closed', master), { kind: 'master', master }, context); + } + } +} diff --git a/packages/objectql/src/closed-state-values.ts b/packages/objectql/src/closed-state-values.ts new file mode 100644 index 00000000000..3c11d608f77 --- /dev/null +++ b/packages/objectql/src/closed-state-values.ts @@ -0,0 +1,23 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1, D2] An object's declared `closedStates`, read as the lock and + * the registry fold read it. Kept apart from the lock (`closed-state-lock.ts`) + * so the registry imports nothing of the engine's write path. + */ + +/** One object's closed values, field → the values of it that close a record. */ +export type ClosedValues = ReadonlyMap>; + +/** An object's declared closed values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ClosedValues | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 327c435f887..5d19e07c2fc 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -43,6 +43,7 @@ * this module. */ +import { judgeClosedStateCascadeSet } from './closed-state-lock.js'; import type { ServiceObject } from '@objectstack/spec/data'; import { SystemFieldName } from '@objectstack/spec/system'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -84,6 +85,13 @@ export interface CascadePlanningHost { readonly drivers: ObjectQLClass['drivers']; fileReferenceCheckElevation: ObjectQLClass['fileReferenceCheckElevation']; find: ObjectQLClass['find']; + /** [ADR-0162 D6] The driver options the closed-state lock reads the cascade set with. */ + buildDriverOptions: ObjectQLClass['buildDriverOptions']; + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; + /** [ADR-0162 D8] The engine, whose security-service slot answers whether the caller is served the root's title. */ + readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; isTenantColumnSetNull: ObjectQLClass['isTenantColumnSetNull']; readonly logger: ObjectQLClass['logger']; @@ -532,7 +540,7 @@ export class CascadePlanningFacet { * (formula values, file references, hooks), so they are not the values a * restore must write back. */ - static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise): Promise { + static async cascadeDeleteRelations(this: Pick, object: string, ids: ReadonlyArray, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise, named: ReadonlyArray = []): Promise { const roots: Array = []; const seen = new Set(); for (const id of ids) { @@ -575,6 +583,13 @@ export class CascadePlanningFacet { // [#26718] Every restrict a member's own cascade would override is judged // here, before the first write. await this.refuseRestrictsInsideOwnCascade(cascadeSet, fresh.map((id) => ({ object, id })), context, objects); + // [ADR-0162 D6] The closed-state lock over the whole set, at the same + // point: after the caller's gates on the record it asked to delete and + // before the first row is removed, never leg by leg. A member that is + // closed, or is a line of a closed record, refuses the delete whole. + // [D8] The refusal's title form reads the ids the delete NAMED (`named`), + // never the set planned so far. + await judgeClosedStateCascadeSet.call(this, object, cascadeSet.members, context, named); if (onCollected) await onCollected(cascadeSet); await this.cascadeDeleteSets.run(cascadeSet, () => this.walkReferencingRelations(object, fresh, context, objects, cascadeSet), diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 73a8727d5da..992dce60e71 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -35,6 +35,7 @@ * this module. */ +import { judgeClosedStateByIdWrite, judgeClosedStatePredicateWrite } from './closed-state-lock.js'; import { normalizeFilterComparandTypes } from '@objectstack/spec/data'; import type { EngineAggregateOptions, EngineDeleteOptions, FilterCondition, HookContext, QueryAST } from '@objectstack/spec/data'; import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts'; @@ -130,12 +131,18 @@ export interface DeleteAndAggregateHost { expandSearchOnOptions: ObjectQLClass['expandSearchOnOptions']; /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */ readonly facade: ObjectQLClass; + /** [ADR-0162 D8] The caller's locale and translator, which the closed-state refusal's sentence is worded in. */ + validationMessageContext: ObjectQLClass['validationMessageContext']; getDriver: ObjectQLClass['getDriver']; getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors']; hasHooksFor: ObjectQLClass['hasHooksFor']; inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit']; invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; openRecycleBinCapture: ObjectQLClass['openRecycleBinCapture']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; planCascadeAtomicity: ObjectQLClass['planCascadeAtomicity']; @@ -159,7 +166,7 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -503,6 +510,13 @@ export class DeleteAndAggregateFacet { // `bindPreImage`'s never-fabricate rule (#4649/#4775) is unchanged and // still the reason the binding goes through it rather than around it. bindPreImage(priorRecord); + // [ADR-0162 D4, D6, D10] The closed-state lock, on the row as stored, + // after the gates and before the before-phase hooks. A cascade leg + // (`referentialCascadeDelete`) is not judged again: its root judged + // the whole set the cascade removes, where the set was planned. + if (referentialCascadeDelete !== true) { + await judgeClosedStateByIdWrite.call(this, { object, verb: 'delete', prior: priorRecord, context: opCtx.context }); + } await this.triggerHooks('beforeDelete', hookContext); // [#6752] The retired lever, refused — the `update()` twin's check, // verbatim, because the rule is now ONE rule: a by-id target is @@ -565,6 +579,26 @@ export class DeleteAndAggregateFacet { // `where: {}` is a REAL (match-all) query and stays on the per-row // authorize path; only an absent or `null` predicate is unscoped. // `update()`'s predicate branch carries the identical check (#9974). + // [ADR-0162 D4, D10] The closed-state lock over every row the composed + // predicate reaches, whole, before any hook runs (the unscoped-multi + // dispatch below included) and before any row is removed. Where the + // store cannot run the line probe it is answered from the one read of + // the doomed rows the hooks below are served from (`readDoomed`). + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); + let doomedRead: Record[] | undefined; + const readDoomed = async (): Promise[]> => { + // [#21613] Each doomed row is its per-row `previous`: declared set. + doomedRead ??= rowsWithDeclaredColumnsOnly( + (await driver.find(object, ast, preOpts) as Record[]) ?? [], + declaredDeleteColumns, + ); + return doomedRead; + }; + if (referentialCascadeDelete !== true) { + await judgeClosedStatePredicateWrite.call(this, { + object, verb: 'delete', ast, driverOptions: preOpts, context: opCtx.context, readMatchedRows: readDoomed, + }); + } const rawWhere = (hookContext.input.options as { where?: unknown } | undefined)?.where; if (rawWhere === undefined || rawWhere === null) { await this.dispatchUnscopedMultiWriteHooks('beforeDelete', object, hookContext); @@ -580,12 +614,7 @@ export class DeleteAndAggregateFacet { // rows: they are its scope check and its per-row realtime events. const cascadeBatch = referentialCascadeDelete === true; if (perRowBeforeHooks || perRowAfterHooks || cascadeBatch) { - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); - // [#21613] Each doomed row is its per-row `previous`: declared set. - const doomed = rowsWithDeclaredColumnsOnly( - (await driver.find(object, ast, preOpts) as Record[]) ?? [], - declaredDeleteColumns, - ); + const doomed = await readDoomed(); predicateMatchedRows = doomed; // [ruling 6893104201 point (2)] The read ran through the AST the // middleware chain composed for this delete, so it is the caller's @@ -686,7 +715,7 @@ export class DeleteAndAggregateFacet { let cascadeChildVanished = false; const runByIdDelete = async (writeContext?: ExecutionContext) => { const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent); - await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected) + await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected, [hookContext.input.id as string | number]) .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); // [ADR-0131 D9] The entry's organization, when neither the record // nor the context names one, is the engine's own system-insert diff --git a/packages/objectql/src/engine-execution-plumbing.ts b/packages/objectql/src/engine-execution-plumbing.ts index 1b890f64e2a..43750ea780d 100644 --- a/packages/objectql/src/engine-execution-plumbing.ts +++ b/packages/objectql/src/engine-execution-plumbing.ts @@ -161,6 +161,9 @@ export function buildSession(execCtx?: ExecutionContext): HookContext['session'] */ export function buildProvenance(execCtx?: ExecutionContext): HookContext['provenance'] { const flowRunId = (execCtx as any)?.flowRunId; + // [ADR-0162 D5, "the hold"] The root run of `flowRunId`'s tree rides beside + // it, and only beside it: a root run id with no run id is no run's write. + const flowRootRunId = flowRunId ? (execCtx as any)?.flowRootRunId : undefined; const attributedUserId = (execCtx as any)?.attributedUserId; const performedBy = (execCtx as any)?.performedBy; const performedByClientId = performedBy?.clientId; @@ -174,6 +177,7 @@ export function buildProvenance(execCtx?: ExecutionContext): HookContext['proven ) return undefined; return { ...(flowRunId ? { flowRunId: String(flowRunId) } : {}), + ...(flowRootRunId ? { flowRootRunId: String(flowRootRunId) } : {}), ...(attributedUserId ? { attributedUserId: String(attributedUserId) } : {}), ...(performedByClientId ? { performedByClientId: String(performedByClientId) } : {}), ...(performedByAgentId ? { performedByAgentId: String(performedByAgentId) } : {}), diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 86f07a674f9..8f545bd8c74 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -35,6 +35,7 @@ * this module. */ +import { judgeClosedStateCreate } from './closed-state-lock.js'; import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import type { DataEngineInsertOptions, EngineCountOptions, EngineQueryOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; @@ -127,6 +128,10 @@ export interface InsertHost { invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; isIssuedAutonumberCollision: ObjectQLClass['isIssuedAutonumberCollision']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; mediaValueShapeStrictFor: ObjectQLClass['mediaValueShapeStrictFor']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; ownershipQueueService: ObjectQLClass['ownershipQueueService']; @@ -329,7 +334,7 @@ export class InsertFacet { } /** The body of `ObjectQL#insert`; the method's docblock there is its contract. */ - static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { + static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterInsert`, or a refusal after a `beforeInsert` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -613,6 +618,15 @@ export class InsertFacet { // context tells a handler whether it is one row of a batch. The scratch // is created once per CALL and shared by every row's context, before and // after — see `HookContext.dispatch`. + // [ADR-0162 D4, D10] The closed-state lock on a create of lines: each + // master the rows name, through the caller's read door first, then its + // stored state. After the gates and the engine's defaults, before the + // before-phase hooks; a many-row create is refused whole. A master a + // `beforeInsert` hook supplies afterwards is not judged here. + await judgeClosedStateCreate.call(this, object, + ((isBatch ? defaultedData : [defaultedData]) as Array | null | undefined>) + .filter((_row, i) => undeclaredPerRow[i] === undefined), + opCtx.context); const insertScope: Record = {}; // ── [#14259] ARM the hook-write recording, one PER ROW ─────────────── // diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 8e7dbc5f68d..0219e3851cc 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -134,7 +134,7 @@ export class ScopedContextFacet { */ static platformSystemApi(this: Pick): ScopedContext { if (this.appAuthored || isDispatchedActionApi(this.facade)) return ScopedContextFacet.sudo.call(this); - const { flowRunId: _run, ...context } = withoutAppAutomationElevation({ ...this.executionContext, isSystem: true }); + const { flowRunId: _run, flowRootRunId: _root, ...context } = withoutAppAutomationElevation({ ...this.executionContext, isSystem: true }); return this.derive(context as ExecutionContext); } diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index ba446ea29e8..8100d37cda7 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -87,6 +87,7 @@ import { } from './engine-top-level.js'; import type { OperationContext, ReferentialClearOption, StoredExpressionServing } from './engine-top-level.js'; import { REFERENTIAL_CLEAR_OPTION } from './engine-top-level.js'; +import { judgeClosedStateByIdWrite, judgeClosedStatePredicateWrite } from './closed-state-lock.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; import { attachRuleMessageRendering } from './engine-rule-message-rendering.js'; @@ -136,6 +137,10 @@ export interface UpdateHost { inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit']; invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; readonly logger: ObjectQLClass['logger']; + /** [ADR-0162 D10] The caller's read door on a named master (the closed-state lock). */ + masterDetailHeadersCallerReads: ObjectQLClass['masterDetailHeadersCallerReads']; + /** [ADR-0162 D4] The tenancy posture, read by the closed-state lock's line probe. */ + resolveEnginePosture: ObjectQLClass['resolveEnginePosture']; mediaValueShapeStrictFor: ObjectQLClass['mediaValueShapeStrictFor']; opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; permissionResolution: ObjectQLClass['permissionResolution']; @@ -171,7 +176,7 @@ export interface UpdateHost { /** The bodies of the "Update" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class UpdateFacet { /** The body of `ObjectQL#update`; the method's docblock there is its contract. */ - static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { + static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -939,6 +944,16 @@ export class UpdateFacet { // permanently true here: it states the invariant, and the invariant // outlives this call site. if (priorRecord) hookContext.previous = coerceBooleanFields(updateSchema as any, priorRecord as any) as any; + // [ADR-0162 D4, D10] The closed-state lock, on the row as stored: + // after the permission and row-access gates (the middleware chain + // has answered) and before the before-phase hooks, so a write + // refused for its own record or its own master runs no app hook. + // Judged by the keys the write carries — the payload as the chain + // left it, the keys the hide pass withheld from the hooks included. + await judgeClosedStateByIdWrite.call(this, { + object, verb: 'update', prior: priorRecord, context: opCtx.context, referentialClear, + payload: { ...(readonlyHiddenFromHooks ?? {}), ...((opCtx.data as Record | null | undefined) ?? {}) }, + }); // [#24619] The stored computed fields over the stored row merged // with the caller's patch, BEFORE the beforeUpdate hooks, so a hook // sees the expression's value over the PRE-strip row. That is not @@ -1009,6 +1024,32 @@ export class UpdateFacet { `write reaches only the rows this caller may edit).`, ); } + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); + readPriorRows = async () => { + if (!priorRowsRead) { + priorRowsRead = true; + // [#21613] The matched rows' pre-images, shaped like the + // by-id prior read: each per-row `afterUpdate` composes its + // `result` from one of them, so both sides stay declared. + priorRows = rowsWithDeclaredColumnsOnly( + (await driver.find(object, ast, preOpts) as Record[]) ?? [], + declaredColumnSet(updateSchema), + ); + } + return priorRows; + }; + + // [ADR-0162 D4, D10] The closed-state lock over every row the + // composed predicate reaches, whole, before any hook runs (the + // unscoped-multi dispatch below included) and any row is written: + // one existence probe on the store, or the one read of the matched + // rows (`readPriorRows`, the memo) where the store cannot run the + // line probe. + await judgeClosedStatePredicateWrite.call(this, { + object, verb: 'update', ast, driverOptions: preOpts, context: opCtx.context, + payload: { ...(readonlyHiddenFromHooks ?? {}), ...((opCtx.data as Record | null | undefined) ?? {}) }, + readMatchedRows: readPriorRows, + }); // [#9974] The unscoped-multi shape check, BEFORE the matched-row // read — `delete()`'s twin (#9719), verbatim in condition, slot and // placement, because the two branches answer the same question about @@ -1041,20 +1082,6 @@ export class UpdateFacet { await dispatchHooksExplainingWithheldReadonly(readonlyHiddenFromHooks, 'beforeUpdate', () => this.dispatchUnscopedMultiWriteHooks('beforeUpdate', object, hookContext)); } - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); - readPriorRows = async () => { - if (!priorRowsRead) { - priorRowsRead = true; - // [#21613] The matched rows' pre-images, shaped like the - // by-id prior read: each per-row `afterUpdate` composes its - // `result` from one of them, so both sides stay declared. - priorRows = rowsWithDeclaredColumnsOnly( - (await driver.find(object, ast, preOpts) as Record[]) ?? [], - declaredColumnSet(updateSchema), - ); - } - return priorRows; - }; // The demand is uniform across hooks and asked PER OBJECT: it is // NOT keyed on whether any condition mentions `previous`, which the diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index b255beec965..772abcaa7a0 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4928,10 +4928,10 @@ export class ObjectQL implements IObjectQLEngine { ids: ReadonlyArray, context?: ExecutionContext, depth = 0, - onCollected?: (set: CascadeDeleteSet) => Promise, + onCollected?: (set: CascadeDeleteSet) => Promise, named?: ReadonlyArray, // [ADR-0162 D8] the ids the delete named ): Promise { // [#29986 codemod] The body moved to `engine-cascade-planning.ts`, its docblock with it (see `CascadePlanningHost`). - return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected); + return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected, named); } /** @@ -5827,7 +5827,7 @@ export class ObjectQL implements IObjectQLEngine { refuseRestrictsInsideOwnCascade: (...a) => engine.refuseRestrictsInsideOwnCascade(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), update: (...a) => engine.update(...a), - walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), + walkReferencingRelations: (...a) => engine.walkReferencingRelations(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), facade: engine, validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D6, D8] })); compatibilitySectionHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -5900,7 +5900,7 @@ export class ObjectQL implements IObjectQLEngine { transaction: (...a) => engine.transaction(...a), triggerHooks: (...a) => engine.triggerHooks(...a), warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), validationMessageContext: (...a) => engine.validationMessageContext(...a), // [ADR-0162 D8, D10] })); findHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -6019,7 +6019,7 @@ export class ObjectQL implements IObjectQLEngine { update: (...a) => engine.update(...a), validationMessageContext: (...a) => engine.validationMessageContext(...a), valueShapeStrictFor: (...a) => engine.valueShapeStrictFor(...a), - warnAutonumberReadersUnserved: (...a) => engine.warnAutonumberReadersUnserved(...a), + warnAutonumberReadersUnserved: (...a) => engine.warnAutonumberReadersUnserved(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] })); middlewareAndContextHost.install((engine) => ({ get _registry() { return engine._registry; }, @@ -6257,7 +6257,7 @@ export class ObjectQL implements IObjectQLEngine { updateByIdExpecting: (...a) => engine.updateByIdExpecting(...a), validationMessageContext: (...a) => engine.validationMessageContext(...a), valueShapeStrictFor: (...a) => engine.valueShapeStrictFor(...a), - withResolvedWhere: (...a) => engine.withResolvedWhere(...a), + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), masterDetailHeadersCallerReads: (...a) => engine.masterDetailHeadersCallerReads(...a), resolveEnginePosture: () => engine.resolveEnginePosture(), // [ADR-0162 D10] })); } } diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 14655b2c3ba..4989d6a5974 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -248,6 +248,13 @@ const READERS: Record = { disposition: 'exempt', why: 'names the related object only to judge the join beside the federated test; it reads no row', }, + // [ADR-0162 D4] The closed-state lock's line probe: a federated master + // declines the composed semi-join, and the lock reads the matched lines + // and their masters by id instead, so no subquery runs against it. + 'closed-state-lock.ts#lineProbeServes :: isFederatedObject()': { + disposition: 'exempt', + why: 'a federated master declines the line probe, so no subquery is compiled against it; it reads no row', + }, // [latest per group] A federated object refuses the one-row-per-group read // before anything is read, so no window is compiled against its remote table. 'latest-per.ts#latestPerRegistryRefusal :: isFederatedObject()': { diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index c8717fa8063..40b46c62d86 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -15,7 +15,8 @@ import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol'; import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core'; import type { MetadataAuthoringChannel } from '@objectstack/metadata-protocol'; -import { Plugin, PluginContext } from '@objectstack/core'; +import { Plugin, PluginContext, isServiceNotRegisteredError } from '@objectstack/core'; +import { SECURITY_SERVICE_REGISTERED_SLOT } from './closed-state-lock.js'; import { resolveArtifactPackageEntries, artifactPackageId, declaredDependencyIds, readDeploymentOrgScopingEntitlement } from '@objectstack/core'; // [ADR-0130 D4] The residual rule's decision half — which top-level items of a // multi-package stack no body declares, and the id they take. See @@ -561,6 +562,40 @@ export const OBJECTQL_DRIVERS_READY_HOOK = 'objectql:drivers-ready'; */ export const OBJECTQL_SCHEMA_SYNCED_HOOK = 'objectql:schema-synced'; +/** + * [ADR-0162 D8] Whether a `security` service is registered on the plugin's + * kernel, read without building one: `false` only when nothing is registered + * under the name, `true` for every other answer (the answer that names no + * title in a closed-state refusal). + * - The sync accessor returns it, or the context's service map holds the + * name: registered. + * - The sync accessor refuses a service registered as a factory and not yet + * built with "is async" (the message the kernel keeps verbatim for callers + * that match on it): registered, and the probe does not build it. + * - Otherwise the kernel's async accessor draws the line with the branded + * "never registered" rejection (`isServiceNotRegisteredError`), given + * before anything is built; any other answer is registered. + * - A host with no async accessor (`LiteKernel`) has no factories, so "not + * registered" is the only fault its sync accessor reports. + */ +async function securityServiceRegistered(ctx: PluginContext): Promise { + try { + ctx.getService('security'); + return true; + } catch (err) { + if (err instanceof Error && err.message.includes('is async')) return true; + } + if (ctx.getServices().has('security')) return true; + const kernel = ctx.getKernel?.() as { getServiceAsync?: (name: string) => Promise } | undefined; + if (typeof kernel?.getServiceAsync !== 'function') return false; + try { + await kernel.getServiceAsync('security'); + return true; + } catch (err) { + return !isServiceNotRegisteredError(err); + } +} + export class ObjectQLPlugin implements Plugin { name = 'com.objectstack.engine.objectql'; type = 'objectql' as const; @@ -923,6 +958,12 @@ export class ObjectQLPlugin implements Plugin { // `$in: []` (fail closed); a throw — the in-repo kernels' answer for a // name nothing registered — is one of them. (this.ql as unknown as Record)[SECURITY_SERVICE_SOURCE_SLOT] = () => ctx.getService('security'); + // [ADR-0162 D8] Beside the source, a probe that answers whether a + // `security` service is registered at all (SECURITY_SERVICE_REGISTERED_SLOT). + // Only the closed-state refusal's title rule reads it, and only when the + // source above throws; it builds no service, so every other reader of the + // source answers as before. + (this.ql as unknown as Record)[SECURITY_SERVICE_REGISTERED_SLOT] = () => securityServiceRegistered(ctx); // [ADR-0142 D5] The assignment seam reads the ownership-queue service the // same way: a source, resolved at use. ⛔ `ownership-queue`, never the job // queue's `queue`. diff --git a/packages/objectql/src/recycle-bin/restore.ts b/packages/objectql/src/recycle-bin/restore.ts index 1575a182347..b5b765d03c9 100644 --- a/packages/objectql/src/recycle-bin/restore.ts +++ b/packages/objectql/src/recycle-bin/restore.ts @@ -67,6 +67,7 @@ * context, as the delete's `set_null` clear went (`engine-cascade-planning.ts`). */ +import { judgeClosedStateRestore } from '../closed-state-lock.js'; import { RECYCLE_BIN_GRANT_KEYS, RECYCLE_BIN_OBJECT, @@ -520,6 +521,8 @@ async function judgeRestore( /** Each master-detail reference whose parent is not live, in row order, and each such parent once. */ const missing: Array<{ row: RecycleBinSnapshotRow; field: string; parent: { object: string; id: string } }> = []; const missingParents = new Map(); + /** [ADR-0162 D7] Each live master a row of the entry comes back under, for the closed-state lock. */ + const liveParents: Array<{ object: string; field: string; master: string; id: string }> = []; for (const row of rows) { const schema = this._registry.getObject(row.object); const fields = fieldsOf(schema); @@ -535,7 +538,10 @@ async function judgeRestore( // restored (its own entry would refuse RESTORE_PACKAGE_UNINSTALLED), so it // is gone for good, whatever the bin holds. if (!this._registry.getObject(parent.object)) throw parentPurgedRefusal(entryId, row, field, parent, true); - if (!missingParents.has(key) && await isLive(parent.object, { id: parent.id })) continue; + if (!missingParents.has(key) && await isLive(parent.object, { id: parent.id })) { + liveParents.push({ object: row.object, field, master: parent.object, id: parent.id }); + continue; + } missing.push({ row, field, parent }); missingParents.set(key, parent); } @@ -552,6 +558,11 @@ async function judgeRestore( if (await isLive(row.object, where)) throw uniqueValueTakenRefusal(entryId, row, field, fieldLabelOf.call(this, row.object, field, context)); } } + // [ADR-0162 D7] Then: no row comes back under a LIVE master that is closed + // and not part of the entry: that is adding a line to a closed document + // through another door. Judged before anything is written; a restore in + // a system context passes. + await judgeClosedStateRestore.call(this, liveParents, context); if (missing.length === 0) return; // 4. The bin, asked once about every missing parent: one not held is purged // (permanent); then, nothing permanent standing, one held is the reason. diff --git a/packages/objectql/src/registry-closed-state-fold.test.ts b/packages/objectql/src/registry-closed-state-fold.test.ts new file mode 100644 index 00000000000..6293b8765c9 --- /dev/null +++ b/packages/objectql/src/registry-closed-state-fold.test.ts @@ -0,0 +1,170 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1] The registry fold keeps a package's `closedStates` honest + * (`registry-closed-state-fold.ts`). + * + * The object's own parse refuses a declaration whose field is gone, retyped, + * multi-value or short of a listed option. The served object is a fold of + * layers the parse never sees together, so the fold holds the same line: + * + * - an extension's redeclaration of a field the declaration names is refused + * where it removes, retypes, makes multi-value or narrows it (one test per + * case), and the rest of the extension still lands; + * - a tenant overlay may add closed values, and may not shorten the + * package's list or break a field it names. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ObjectQL } from './engine.js'; + +const OWNER_PKG = 'com.example.billing'; +const EXT_PKG = 'com.example.ext'; + +const STATUS = { + type: 'select', + label: 'Status', + options: [ + { label: 'Draft', value: 'draft' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, + ], +}; + +const owner = () => ({ + name: 'cs_invoice', + label: 'Invoice', + fields: { name: { type: 'text', label: 'Number' }, status: STATUS }, + closedStates: { status: ['paid', 'void'] }, +}); + +function makeDriver() { + return { + name: 'com.objectstack.driver.memory.cs-fold', + version: '1.0.0', + async connect() {}, async disconnect() {}, async initObjects() {}, + async find() { return []; }, async findOne() { return null; }, async count() { return 0; }, + async create(_o: string, d: unknown) { return d; }, async update(_o: string, d: unknown) { return d; }, async delete() { return false; }, + } as any; +} + +let engine: ObjectQL; +async function boot(): Promise { + engine = new ObjectQL(); + engine.registerDriver(makeDriver(), true); + await engine.init(); +} +afterEach(async () => { try { await engine?.destroy(); } catch { /* noop */ } vi.restoreAllMocks(); }); + +const served = () => engine.registry.getObject('cs_invoice') as any; + +describe('[ADR-0162 D1] an extension cannot break a field the served closedStates names', () => { + const cases: ReadonlyArray, string]> = [ + ['retypes it', { type: 'text', label: 'Status' }, 'retypes it as `text`'], + ['makes it multi-value', { ...STATUS, multiple: true }, 'makes it a multi-value select'], + ['narrows its options past a listed value', { ...STATUS, options: STATUS.options.slice(0, 2) }, "drops the listed option 'void'"], + ['leaves it with no inline options', { type: 'select', label: 'Status', picklist: 'other' }, 'leaves it with no inline options'], + ]; + for (const [label, redeclared, said] of cases) { + it(`refuses an extension that ${label}, and applies the rest of the extension`, async () => { + await boot(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + engine.registry.registerObject({ + name: 'cs_invoice', + fields: { status: redeclared, memo: { type: 'text', label: 'Memo' } }, + } as any, EXT_PKG, undefined, 'extend'); + const obj = served(); + expect(obj.fields.status).toEqual(STATUS); + expect(obj.fields.memo?.type).toBe('text'); + expect(obj.closedStates).toEqual({ status: ['paid', 'void'] }); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('closedStates')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(said); + expect(lines[0]).toContain(EXT_PKG); + }); + } + + it('CONTROL: an extension that adds an option to the named field lands', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const wider = { ...STATUS, options: [...STATUS.options, { label: 'Refunded', value: 'refunded' }] }; + engine.registry.registerObject({ name: 'cs_invoice', fields: { status: wider } } as any, EXT_PKG, undefined, 'extend'); + expect(served().fields.status.options.map((o: { value: string }) => o.value)).toEqual(['draft', 'paid', 'void', 'refunded']); + }); + + it('CONTROL: an object no layer declares closedStates on folds as before', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { closedStates: _none, ...plain } = owner(); + engine.registry.registerObject(plain as any, OWNER_PKG); + engine.registry.registerObject({ name: 'cs_invoice', fields: { status: { type: 'text', label: 'Status' } } } as any, EXT_PKG, undefined, 'extend'); + expect(served().fields.status.type).toBe('text'); + expect(served().closedStates).toBeUndefined(); + }); +}); + +describe('[ADR-0162 D1] a tenant overlay may add closed values, and may not shorten the package\'s list', () => { + const overlay = (body: Record) => + engine.registry.registerObject({ ...body, _provenance: 'org' } as any, OWNER_PKG, undefined, 'overlay'); + + it('may ADD: an overlay that declares closed values of its own is served with them', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), closedStates: { status: ['paid', 'void', 'draft'] } }); + expect(served().closedStates).toEqual({ status: ['paid', 'void', 'draft'] }); + }); + + it('may add a declaration to a package object that has none', async () => { + await boot(); + const { closedStates: _none, ...plain } = owner(); + engine.registry.registerObject(plain as any, OWNER_PKG); + overlay({ ...plain, closedStates: { status: ['void'] } }); + expect(served().closedStates).toEqual({ status: ['void'] }); + }); + + it('may not shorten: an overlay that leaves the key out, or lists less, is served the package\'s list', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const { closedStates: _dropped, ...withoutKey } = owner(); + overlay(withoutKey); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + + it('may not shorten by listing fewer values', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), closedStates: { status: ['paid'] } }); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + + it('may not break the named field: an overlay that drops a listed option is served the package\'s field', async () => { + await boot(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + const { closedStates: _dropped, ...rest } = owner(); + overlay({ ...rest, fields: { ...rest.fields, status: { ...STATUS, options: STATUS.options.slice(0, 2) } } }); + expect(served().fields.status).toEqual(STATUS); + expect(warn.mock.calls.map((c) => String(c[0])).some((m) => m.includes("drops the listed option 'void'"))).toBe(true); + }); + + it('a value the overlay added for its own version of a restored field is not served', async () => { + await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + engine.registry.registerObject(owner() as any, OWNER_PKG); + // The overlay drops 'void' and adds 'refunded', and lists 'refunded' as closed. + const broken = { ...STATUS, options: [...STATUS.options.slice(0, 2), { label: 'Refunded', value: 'refunded' }] }; + overlay({ ...owner(), fields: { ...owner().fields, status: broken }, closedStates: { status: ['paid', 'void', 'refunded'] } }); + expect(served().fields.status).toEqual(STATUS); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); + + it('CONTROL: an overlay that only relabels keeps its label and the package\'s list', async () => { + await boot(); + engine.registry.registerObject(owner() as any, OWNER_PKG); + overlay({ ...owner(), label: 'Customer invoice' }); + expect(served().label).toBe('Customer invoice'); + expect(served().closedStates).toEqual({ status: ['paid', 'void'] }); + }); +}); diff --git a/packages/objectql/src/registry-closed-state-fold.ts b/packages/objectql/src/registry-closed-state-fold.ts new file mode 100644 index 00000000000..5edf2ebab7a --- /dev/null +++ b/packages/objectql/src/registry-closed-state-fold.ts @@ -0,0 +1,124 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D1] The registry fold keeps a `closedStates` declaration honest. + * + * The object's own parse refuses a declaration that names a field which is + * missing, not a single-value `select`, or lacks one of the listed options + * (`packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates`). The + * served object is not one document, though: the fold lays a tenant overlay + * base and other packages' `extend` bodies over the owner's + * (`registry-object-registration.ts#foldExtendersOntoDefinition`), and the + * object's refinement is not run again over the result. Two layers could then + * take from a package's declaration what its own parse protects: + * + * - **An extension** that redeclares, in its `fields`, a field the served + * declaration names, as another type, as a multi-value select, or with + * options that leave out a listed value. Its redeclaration of THAT field is + * refused at the fold: the field the fold had stands, and the fold says so + * once in the log. The rest of the extension is applied as before. + * - **A tenant overlay** (the base the fold starts from, ADR-0029 D9.2). It + * may add closed values of its own, which an overlay body can always carry; + * it may not shorten a package's own list. The served declaration is the + * package's, with the overlay's added to it, and a field the package's list + * names keeps the package's definition where the overlay removed it, + * retyped it, made it multi-value or dropped a listed option. + * + * Neither changes an object no layer declares `closedStates` on. + */ + +import { closedValuesOf, type ClosedValues } from './closed-state-values.js'; + +type Body = { name?: unknown; fields?: Record; closedStates?: Record }; + +/** Why `field` cannot carry `listed`, or `undefined` when it can. */ +export function closedStateFieldBreach(field: unknown, listed: ReadonlySet): string | undefined { + if (!field || typeof field !== 'object') return 'removes it'; + const def = field as { type?: unknown; multiple?: unknown; options?: unknown }; + if (def.type !== 'select') return `retypes it as \`${String(def.type)}\``; + if (def.multiple === true) return 'makes it a multi-value select'; + if (!Array.isArray(def.options)) return 'leaves it with no inline options'; + const values = optionValuesOf(def); + const dropped = [...listed].filter((v) => !values.has(v)); + if (dropped.length > 0) return `drops the listed option${dropped.length > 1 ? 's' : ''} ${dropped.map((v) => `'${v}'`).join(', ')}`; + return undefined; +} + +/** + * The extension body with every redeclaration of a field the running + * declaration names removed where it would break that declaration. Answers the + * body itself when nothing is refused. + */ +export function withoutClosedStateFieldBreaches(running: Body, extension: T, packageId: string | undefined): T { + const closed = closedValuesOf(running); + const fields = extension.fields; + if (!closed || !fields || typeof fields !== 'object') return extension; + let kept: Record | undefined; + for (const [name, listed] of closed) { + if (!Object.prototype.hasOwnProperty.call(fields, name)) continue; + const breach = closedStateFieldBreach(fields[name], listed); + if (breach === undefined) continue; + kept ??= { ...fields }; + delete kept[name]; + console.warn( + `[Registry] An extension of object "${String(running.name ?? extension.name ?? '')}"` + + `${packageId ? ` from package "${packageId}"` : ''} redeclares field "${name}" in a way that ${breach}, ` + + 'and the object\'s `closedStates` names that field. The redeclaration is refused and the field stands as the ' + + 'fold had it: a closed-state declaration names a stored single-value `select` and its own options. ' + + 'Patch the field\'s display properties instead (`fieldPatches`), or add options without removing a listed one.', + ); + } + return kept ? { ...extension, fields: kept } : extension; +} + +function optionValuesOf(field: unknown): Set { + const options = field && typeof field === 'object' ? (field as { options?: unknown }).options : undefined; + return new Set(Array.isArray(options) ? options.map((o) => (o && typeof o === 'object' ? (o as { value?: unknown }).value : o)) : []); +} + +/** `a` with every value of `b` added, per field. */ +function unionClosed(a: ClosedValues, b: ClosedValues | undefined): Record { + const out: Record = {}; + for (const [field, values] of a) out[field] = [...values]; + for (const [field, values] of b ?? []) { + const list = out[field] ?? (out[field] = []); + for (const v of values) if (!list.includes(v)) list.push(v); + } + return out; +} + +/** + * The fold's base where it is a tenant overlay over a package's object: the + * package's `closedStates` kept whole, the overlay's own values added, and the + * package's definition kept for each field its list names where the overlay + * broke it. Answers `base` itself when the owner declares nothing or the base + * is the owner's own body. + */ +export function withPackagedClosedStates(owner: Body | undefined, base: T): T { + if (!owner || owner === base) return base; + const packaged = closedValuesOf(owner); + if (!packaged) return base; + const out: T = { ...base, closedStates: unionClosed(packaged, closedValuesOf(base)) }; + const fields = base.fields && typeof base.fields === 'object' ? { ...base.fields } : {}; + let restored = false; + for (const [name, listed] of packaged) { + const breach = closedStateFieldBreach(fields[name], listed); + if (breach === undefined) continue; + const ownerField = owner.fields?.[name]; + if (ownerField === undefined) continue; + fields[name] = ownerField; + restored = true; + // The package's field is served, so the overlay's values for it are kept + // only where that field declares them: a value only the overlay's own + // version of the field offered would be served in a list naming no option. + const declared = optionValuesOf(ownerField); + out.closedStates![name] = out.closedStates![name].filter((v) => listed.has(v) || declared.has(v)); + console.warn( + `[Registry] Field "${name}" of object "${String(base.name ?? owner.name ?? '')}": the tenant overlay ${breach}, ` + + 'and the package\'s `closedStates` names the field. The package\'s definition of the field stands: an overlay may add ' + + 'closed values of its own, and may not shorten or break the package\'s list.', + ); + } + if (restored) out.fields = fields; + return out; +} diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index a2ec45ab3cd..42865b32a73 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -45,6 +45,7 @@ * this module. */ +import { withPackagedClosedStates, withoutClosedStateFieldBreaches } from './registry-closed-state-fold.js'; import { BASE_FIELD_DISPLAY_WHITELIST, isInjectedColumnDefinition, materializeTreeSelfReferences, provisionPrimary, resolveInjectedSystemColumns } from '@objectstack/spec/data'; import type { ObjectOwnership, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, installedManifestsOf, isCodeArtifactBody, isTenantAuthored, pairsOf } from '@objectstack/metadata-core'; @@ -927,6 +928,9 @@ export class ObjectRegistrationFacet { let merged = tenantRules ? this.withPackagedOwnerRules(contributors, baseDefinition, tenantRules) : { ...baseDefinition }; + // [ADR-0162 D1] A tenant overlay base may add closed values of its own + // and may not shorten the package's list, or break a field it names. + if (owner && owner !== baseDefinition) merged = withPackagedClosedStates(owner, merged); // [#28835] Each extension's `fields` as the merge took them, in fold order. const folded: FoldedExtensionFields[] = []; for (const contrib of contributors) { @@ -950,7 +954,9 @@ export class ObjectRegistrationFacet { const admitted = misses.length > 0 ? { ...extension, fieldPatches: admittedFieldPatches(patches!, misses) } as ObjectExtensionBody : extension; - merged = mergeObjectDefinitions(merged, admitted, tenantAuthored, tenantRules, tenantPatched, ownFields); + // [ADR-0162 D1] An extension's redeclaration of a field the served + // `closedStates` names is refused where it would break the declaration. + merged = mergeObjectDefinitions(merged, withoutClosedStateFieldBreaches(merged, admitted, contrib.packageId), tenantAuthored, tenantRules, tenantPatched, ownFields); // [#28809] …and the same judge once more, over the admitted patches // against the owner's fields as MERGED, which only names: an admitted // option an earlier layer left out (an extension's `fields` diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 459ff57f73a..4a7ef4bc8f2 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const arMetadataForms: NonNullable = { label: "السجل كله للقراءة فقط في الواجهة عندما", helpText: "شرط CEL على السجل (مثل record.status in ['confirmed', 'done']) — ما دام TRUE لا يستطيع أحد تعديل أي حقل من سجل موجود في وحدة التحكم (مربع حوار التعديل، صفحة السجل، الجداول، كانبان، السحب في التقويم ومخطط جانت، جدول الدوام)؛ ولا يُقيَّم مربع حوار إنشاء سجل جديد. الحقل الذي يعلن قفله اليدوي الخاص (تفعيل uiReadonly، أو uiReadonlyWhen) يُحكم عليه بإعلانه، لذا فإن uiReadonlyWhen: false على حقل يبقيه قابلاً للتعديل؛ أما إيقاف uiReadonly فلا يُحتسب، ويتبع الحقل هذا القفل. تستمر الإجراءات والاستيراد وواجهة API والتدفقات في كتابة كل حقل، وتحكم عليها قواعد التحقق للكائن. يقرأ أعمدة السجل نفسه. المساعد داخل التطبيق الذي يعمل نيابة عن شخص لا يلتزم بهذا بعد." }, + closedStates: { + label: "الحالات المغلقة", + helpText: "الحالات التي يكون فيها السجل مغلقًا، في صورة خريطة من حقل اختيار أحادي القيمة في هذا الكائن إلى قائمة قيم خياراته التي تغلق السجل، مثل { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. ما دام السجل مغلقًا فلا يستطيع أحد غير النظام تعديله أو حذفه، ولا إضافة بنوده أو تعديلها أو نقلها أو إزالتها. يجب أن يعلن كل حقل خياراته بنفسه، وأن تكون كل قيمة واحدة منها مذكورة مرة واحدة. لا يمكن حذف حقل أو خيار مذكور هنا أو تغيير نوعه حتى يُزال من هذه الخريطة." + }, activityMilestones: { label: "معالم النشاط", helpText: "إدخالات في الخط الزمني يُطلقها وصول حقل إلى قيمة (ADR-0052 §5b.2): عندما ينقل تحديثٌ الحقلَ المراقَب إلى القيمة، يكتب مكوّن التدقيق الإضافي ملخّص المَعلم في الخط الزمني لنشاط السجل بدلًا من إدخال تغيير الحقل. يفوز أول مَعلم يطابق." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index c99cdb444bc..c393a0301dc 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const deMetadataForms: NonNullable = { label: "Ganzer Datensatz in der Oberfläche schreibgeschützt wenn", helpText: "CEL-Prädikat über den Datensatz (z. B. record.status in ['confirmed', 'done']) – solange es TRUE ist, kann niemand in der Konsole ein Feld eines bestehenden Datensatzes bearbeiten (Bearbeitungsdialog, Datensatzseite, Tabellen, Kanban, Kalender- und Gantt-Ziehen, Zeiterfassung); der Erstellungsdialog eines neuen Datensatzes wird nicht geprüft. Ein Feld, das eine eigene manuelle Sperre (uiReadonly eingeschaltet oder uiReadonlyWhen) festlegt, wird stattdessen danach beurteilt, sodass uiReadonlyWhen: false an einem Feld es bearbeitbar hält; ein ausgeschaltetes uiReadonly zählt nicht, und das Feld folgt dieser Sperre. Aktionen, Importe, die API und Flows schreiben weiterhin jedes Feld, beurteilt durch die Validierungen des Objekts. Liest die eigenen Spalten des Datensatzes. Der In-App-Assistent, der für eine Person handelt, beachtet dies noch nicht." }, + closedStates: { + label: "Abgeschlossene Zustände", + helpText: "Zustände, in denen ein Datensatz abgeschlossen ist, als Zuordnung von einem einwertigen Auswahlfeld dieses Objekts zur Liste seiner Optionswerte, die den Datensatz abschließen, z. B. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Solange ein Datensatz abgeschlossen ist, kann ihn niemand außer dem System bearbeiten oder löschen, und niemand kann seine Positionen hinzufügen, bearbeiten, verschieben oder entfernen. Jedes Feld muss seine Optionen selbst deklarieren; jeder Wert muss eine davon sein und darf nur einmal aufgeführt werden. Ein hier genanntes Feld oder eine hier genannte Option kann erst entfernt oder umtypisiert werden, wenn es aus dieser Zuordnung herausgenommen wurde." + }, activityMilestones: { label: "Aktivitätsmeilensteine", helpText: "Zeitleisteneinträge, die ausgelöst werden, wenn ein Feld einen Wert erreicht (ADR-0052 §5b.2): Wenn eine Aktualisierung das beobachtete Feld auf den Wert setzt, schreibt das Audit-Plugin die Zusammenfassung des Meilensteins statt des Feldänderungseintrags in die Aktivitätszeitleiste des Datensatzes. Der erste passende Meilenstein gewinnt." diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index a0590352051..e6ccad13467 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const enMetadataForms: NonNullable = { label: "Ui Readonly When", helpText: "CEL predicate over the record (e.g. record.status in ['confirmed', 'done']) — while it is TRUE, people cannot edit any field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. A field that sets its own hand lock (uiReadonly turned on, or uiReadonlyWhen) is judged by that instead, so uiReadonlyWhen: false on a field keeps it editable; uiReadonly turned off does not, and the field follows this lock. Actions, imports, the API and flows still write every field, judged by the object's validations. Reads the record's own columns. The in-app assistant acting for a person does not honour it yet." }, + closedStates: { + label: "Closed States", + helpText: "States in which a record is closed, as a map from a single-value select field of this object to the list of its option values that close the record, e.g. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. While a record is closed, no one but the system edits or deletes it, or adds, edits, moves or removes its lines. Each field needs its options declared on it; each value must be one of them, listed once. A field or option named here cannot be removed or retyped until it is taken out of this map." + }, activityMilestones: { label: "Activity Milestones", helpText: "Timeline entries fired by a field reaching a value (ADR-0052 §5b.2): when an update moves the watched field into the value, the audit plugin writes the milestone's summary to the record's activity timeline instead of the field-change entry. The first milestone that matches wins." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 3d06b37476c..9927aad6541 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const esESMetadataForms: NonNullable = label: "Condición de solo lectura en la interfaz para todo el registro", helpText: "Predicado CEL sobre el registro (p. ej. record.status in ['confirmed', 'done']): mientras sea TRUE, nadie puede editar ningún campo de un registro existente en la consola (el diálogo de edición, la página del registro, las cuadrículas, el kanban, el arrastre del calendario y del Gantt, la hoja de horas); el diálogo de creación de un registro nuevo no se evalúa. Un campo que declara su propio bloqueo manual (uiReadonly activado, o uiReadonlyWhen) se juzga por él, así que uiReadonlyWhen: false en un campo lo mantiene editable; uiReadonly desactivado no cuenta y el campo sigue este bloqueo. Las acciones, las importaciones, la API y los flujos siguen escribiendo todos los campos, juzgados por las validaciones del objeto. Lee las columnas propias del registro. El asistente integrado que actúa por una persona aún no lo respeta." }, + closedStates: { + label: "Estados cerrados", + helpText: "Estados en los que un registro está cerrado, como un mapa de un campo de selección de valor único de este objeto a la lista de sus valores de opción que cierran el registro, p. ej. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Mientras un registro está cerrado, nadie salvo el sistema puede editarlo ni eliminarlo, ni añadir, editar, mover o quitar sus líneas. Cada campo debe declarar sus propias opciones; cada valor debe ser una de ellas y figurar una sola vez. Un campo u opción indicado aquí no se puede eliminar ni cambiar de tipo hasta que se quite de este mapa." + }, activityMilestones: { label: "Hitos de actividad", helpText: "Entradas de la cronología que se disparan cuando un campo alcanza un valor (ADR-0052 §5b.2): cuando una actualización cambia el campo vigilado a ese valor, el plugin de auditoría escribe el resumen del hito en la cronología de actividad del registro en lugar de la entrada de cambio de campo. Gana el primer hito que coincide." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 636947ba180..86284881ec3 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const frMetadataForms: NonNullable = { label: "Enregistrement entier en lecture seule dans l'interface si", helpText: "Prédicat CEL sur l'enregistrement (par ex. record.status in ['confirmed', 'done']) — tant qu'il est TRUE, personne ne peut modifier un champ d'un enregistrement existant dans la console (boîte de dialogue de modification, page de l'enregistrement, grilles, kanban, glisser-déposer du calendrier et du Gantt, feuille de temps) ; la boîte de dialogue de création d'un nouvel enregistrement n'est pas évaluée. Un champ qui déclare son propre verrou manuel (uiReadonly activé, ou uiReadonlyWhen) est jugé par celui-ci, donc uiReadonlyWhen: false sur un champ le garde modifiable ; uiReadonly désactivé ne compte pas, et le champ suit ce verrou. Les actions, les imports, l'API et les flux écrivent toujours chaque champ, jugés par les validations de l'objet. Lit les colonnes propres de l'enregistrement. L'assistant intégré agissant pour une personne ne le respecte pas encore." }, + closedStates: { + label: "États clôturés", + helpText: "États dans lesquels un enregistrement est clôturé, sous forme d’une correspondance entre un champ de sélection à valeur unique de cet objet et la liste de ses valeurs d’option qui clôturent l’enregistrement, par ex. { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Tant qu’un enregistrement est clôturé, personne d’autre que le système ne peut le modifier ou le supprimer, ni ajouter, modifier, déplacer ou supprimer ses lignes. Chaque champ doit déclarer ses propres options ; chaque valeur doit être l’une d’elles, citée une seule fois. Un champ ou une option cité ici ne peut être supprimé ni changer de type tant qu’il n’est pas retiré de cette correspondance." + }, activityMilestones: { label: "Jalons d’activité", helpText: "Entrées de chronologie déclenchées lorsqu’un champ atteint une valeur (ADR-0052 §5b.2) : lorsqu’une mise à jour fait passer le champ surveillé à cette valeur, le plugin d’audit écrit le résumé du jalon dans la chronologie d’activité de l’enregistrement au lieu de l’entrée de modification de champ. Le premier jalon qui correspond l’emporte." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 83dd9038879..32c221bb231 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const jaJPMetadataForms: NonNullable = label: "レコード全体を画面上で読み取り専用にする条件", helpText: "レコードに対する CEL 述語(例: record.status in ['confirmed', 'done'])。TRUE の間、コンソールのどこでも既存レコードのどのフィールドも人が編集できません(編集ダイアログ、レコードページ、グリッド、カンバン、カレンダーとガントのドラッグ、タイムシート)。新規レコードの作成ダイアログは判定されません。独自の手動ロック(uiReadonly をオン、または uiReadonlyWhen)を宣言したフィールドはその宣言で判定されるため、フィールドに uiReadonlyWhen: false を設定すると編集可能なままになります。uiReadonly をオフにしてもそうはならず、フィールドはこのロックに従います。アクション、インポート、API、フローは引き続きすべてのフィールドに書き込み、オブジェクトの検証ルールで判定されます。レコード自身の列を読み取ります。ユーザーの代わりに操作するアプリ内アシスタントはまだこの設定に従いません。" }, + closedStates: { + label: "クローズ状態", + helpText: "レコードがクローズされる状態。このオブジェクトの単一値の選択フィールドから、レコードをクローズさせるそのオプション値のリストへのマップです。例: { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。レコードがクローズされている間は、システム以外の誰もそのレコードを編集・削除できず、明細行の追加・編集・移動・削除もできません。各フィールドは自身にオプションを宣言している必要があり、各値はそのいずれかで、一度だけ記載します。ここで指定したフィールドやオプションは、このマップから外すまで削除や型の変更ができません。" + }, activityMilestones: { label: "アクティビティのマイルストーン", helpText: "フィールドが特定の値に達したときに書き込まれるタイムラインのエントリ(ADR-0052 §5b.2)。更新で監視対象のフィールドがその値に変わると、監査プラグインはフィールド変更のエントリの代わりに、マイルストーンの概要をレコードのアクティビティタイムラインに書き込みます。最初に一致したマイルストーンが使われます。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 7f7aa548caa..4f00e2598e6 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const koMetadataForms: NonNullable = { label: "레코드 전체를 화면에서 읽기 전용으로 하는 조건", helpText: "레코드에 대한 CEL 조건식(예: record.status in ['confirmed', 'done']) — TRUE인 동안 콘솔 어디에서도 기존 레코드의 어떤 필드도 사람이 편집할 수 없습니다(편집 대화상자, 레코드 페이지, 그리드, 칸반, 캘린더와 간트 드래그, 타임시트). 새 레코드의 생성 대화상자는 판정하지 않습니다. 자체 수동 잠금(uiReadonly 켜기 또는 uiReadonlyWhen)을 선언한 필드는 그 선언으로 판정되므로, 필드에 uiReadonlyWhen: false를 두면 편집 가능한 상태로 유지됩니다. uiReadonly를 끈 것은 해당하지 않으며 필드는 이 잠금을 따릅니다. 작업, 가져오기, API, 플로는 여전히 모든 필드에 쓰며 객체의 검증 규칙이 판정합니다. 레코드 자체의 열을 읽습니다. 사용자를 대신해 작업하는 앱 내 어시스턴트는 아직 이 설정을 따르지 않습니다." }, + closedStates: { + label: "마감 상태", + helpText: "레코드가 마감되는 상태입니다. 이 객체의 단일 값 선택 필드를 레코드를 마감시키는 해당 옵션 값 목록에 매핑합니다. 예: { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. 레코드가 마감된 동안에는 시스템 외에는 누구도 레코드를 편집하거나 삭제할 수 없고, 상세 행을 추가, 편집, 이동, 삭제할 수도 없습니다. 각 필드는 자체에 옵션을 선언해야 하며, 각 값은 그중 하나여야 하고 한 번만 나열합니다. 여기에 지정된 필드나 옵션은 이 매핑에서 빼기 전까지 삭제하거나 유형을 바꿀 수 없습니다." + }, activityMilestones: { label: "활동 마일스톤", helpText: "필드가 특정 값에 도달하면 발생하는 타임라인 항목입니다(ADR-0052 §5b.2). 업데이트로 감시 대상 필드가 그 값으로 바뀌면, 감사 플러그인이 필드 변경 항목 대신 마일스톤의 요약을 레코드 활동 타임라인에 기록합니다. 처음 일치하는 마일스톤이 우선합니다." diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index ba12af10577..91316f25fe9 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -974,10 +974,13 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // `selection` (the multi-select bar's order) — a label and a help text, // translated in zh-CN, ja-JP and es-ES by that card. `advanced` reads // 114 → 116. - expect(PANEL_LEAVES.length).toBe(129); + // 131 since ADR-0162 D1 gave `advanced` the object's closed states + // (`closedStates`) — a label and a help text, two leaves, all translated + // leaves authored in every locale by that card. `advanced` reads 116 → 118. + expect(PANEL_LEAVES.length).toBe(131); expect(PANEL_LEAVES.every((l) => l.prop === 'label' || l.prop === 'helpText')).toBe(true); expect(PANEL_LEAVES.filter((l) => l.section === 'capabilities').length).toBe(13); - expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(116); + expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(118); }); it('⭐ DARK, OUTWARD — the open sections are excluded, and `fields.placeholder` is the one that proves it', () => { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index c5a78fcaad8..b7d17ace88e 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1369,7 +1369,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 875 since #37802: the object form's `fieldTabs` repeater (the record // page's field tabs) — the row and its `key` and `groups` sub-rows, // three labels, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(875); + // 876 since ADR-0162 D1: the object form's `closedStates` row (the + // states that close a record), authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(876); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 85188b9f2b1..800dbcd16fe 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const ptBRMetadataForms: NonNullable = label: "Registro inteiro somente leitura na interface quando", helpText: "Predicado CEL sobre o registro (por exemplo, record.status in ['confirmed', 'done']) — enquanto for TRUE, ninguém pode editar nenhum campo de um registro existente no console (o diálogo de edição, a página do registro, grades, kanban, arrastar no calendário e no Gantt, a planilha de horas); o diálogo de criação de um novo registro não é avaliado. Um campo que declara seu próprio bloqueio manual (uiReadonly ativado, ou uiReadonlyWhen) é julgado por ele, então uiReadonlyWhen: false em um campo o mantém editável; uiReadonly desativado não conta, e o campo segue este bloqueio. Ações, importações, a API e fluxos continuam gravando todos os campos, julgados pelas validações do objeto. Lê as colunas do próprio registro. O assistente no aplicativo que age por uma pessoa ainda não respeita isso." }, + closedStates: { + label: "Estados fechados", + helpText: "Estados em que um registro está fechado, como um mapa de um campo de seleção de valor único deste objeto para a lista dos seus valores de opção que fecham o registro, por exemplo { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Enquanto um registro está fechado, ninguém além do sistema pode editá-lo ou excluí-lo, nem adicionar, editar, mover ou remover suas linhas. Cada campo precisa declarar as próprias opções; cada valor deve ser uma delas, listado uma única vez. Um campo ou opção citado aqui não pode ser removido nem ter o tipo alterado até ser retirado deste mapa." + }, activityMilestones: { label: "Marcos de atividade", helpText: "Entradas da linha do tempo disparadas quando um campo atinge um valor (ADR-0052 §5b.2): quando uma atualização leva o campo observado para o valor, o plugin de auditoria grava o resumo do marco na linha do tempo de atividades do registro em vez da entrada de alteração de campo. O primeiro marco correspondente vence." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 0dfbad5ec73..a100b0a30d4 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const ruMetadataForms: NonNullable = { label: "Вся запись только для чтения в интерфейсе, когда", helpText: "Предикат CEL над записью (например, record.status in ['confirmed', 'done']) — пока он TRUE, никто не может изменить ни одно поле существующей записи в консоли (диалог редактирования, страница записи, таблицы, канбан, перетаскивание в календаре и диаграмме Ганта, табель); диалог создания новой записи не проверяется. Поле, объявившее собственную ручную блокировку (включённый uiReadonly или uiReadonlyWhen), оценивается по ней, поэтому uiReadonlyWhen: false у поля оставляет его редактируемым; выключенный uiReadonly не считается, и поле следует этой блокировке. Действия, импорт, API и потоки по-прежнему записывают каждое поле, и их оценивают проверки объекта. Читает собственные столбцы записи. Встроенный помощник, действующий от имени человека, пока это не учитывает." }, + closedStates: { + label: "Закрытые состояния", + helpText: "Состояния, в которых запись закрыта: сопоставление однозначного поля выбора этого объекта со списком его значений вариантов, которые закрывают запись, например { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }. Пока запись закрыта, никто, кроме системы, не может её изменить или удалить, а также добавить, изменить, переместить или удалить её строки. Каждое поле должно само объявлять свои варианты; каждое значение должно быть одним из них и указываться один раз. Поле или вариант, указанные здесь, нельзя удалить или сменить им тип, пока они не убраны из этого сопоставления." + }, activityMilestones: { label: "Вехи активности", helpText: "Записи ленты, создаваемые, когда поле достигает значения (ADR-0052 §5b.2): когда обновление переводит отслеживаемое поле в это значение, плагин аудита записывает в ленту активности записи сводку вехи вместо записи об изменении поля. Побеждает первая подходящая веха." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 37900d8e32d..9697e502a00 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const zhCNMetadataForms: NonNullable = label: "记录界面只读条件", helpText: "基于记录的 CEL 谓词(例如 record.status in ['confirmed', 'done'])——为 TRUE 时,用户无法在控制台中编辑已有记录的任何字段(编辑对话框、记录页、表格、看板、日历和甘特图拖动、工时表);新建记录的创建对话框不做判断。自行声明了手动锁定(开启 uiReadonly,或 uiReadonlyWhen)的字段按其自身声明裁决,因此字段上的 uiReadonlyWhen: false 可让它保持可编辑;关闭 uiReadonly 不算,字段仍随此锁定。动作、导入、API 和流程仍可写入每个字段,并由对象的校验规则裁决。读取记录自身的列。代表用户操作的应用内助手暂不遵循此设置。" }, + closedStates: { + label: "已关闭状态", + helpText: "记录处于已关闭状态的条件:一个映射,键为本对象的单值选择字段,值为使记录关闭的选项值列表,例如 { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。记录关闭后,除系统外任何人都不能编辑或删除它,也不能新增、编辑、移动或删除它的明细行。每个字段都必须在自身上声明选项;每个值必须是其中之一,且只列一次。这里列出的字段或选项,在从此映射中移除之前不能删除或更改类型。" + }, activityMilestones: { label: "活动里程碑", helpText: "由字段到达某个值触发的时间线条目(ADR-0052 §5b.2):当一次更新把被监视的字段变为该值时,审计插件会把该里程碑的摘要写入记录的活动时间线,代替字段变更条目。第一个匹配的里程碑生效。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 0092f8e835e..734f298cdc0 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -445,6 +445,10 @@ export const zhHantMetadataForms: NonNullable label: "記錄介面唯讀條件", helpText: "基於記錄的 CEL 述詞(例如 record.status in ['confirmed', 'done'])——為 TRUE 時,使用者無法在主控台中編輯既有記錄的任何欄位(編輯對話框、記錄頁、表格、看板、行事曆與甘特圖拖曳、工時表);新記錄的建立對話框不做判斷。自行宣告了手動鎖定(開啟 uiReadonly,或 uiReadonlyWhen)的欄位依其自身宣告裁決,因此欄位上的 uiReadonlyWhen: false 可讓它保持可編輯;關閉 uiReadonly 不算,欄位仍隨此鎖定。動作、匯入、API 與流程仍可寫入每個欄位,並由物件的驗證規則裁決。讀取記錄自身的欄。代表使用者操作的應用程式內助理暫不遵循此設定。" }, + closedStates: { + label: "已關閉狀態", + helpText: "記錄處於已關閉狀態的條件:一個對應表,鍵為本物件的單值選擇欄位,值為使記錄關閉的選項值清單,例如 { \"status\": [\"paid\", \"void\"], \"approval_status\": [\"approved\"] }。記錄關閉後,除系統外任何人都不能編輯或刪除它,也不能新增、編輯、移動或刪除它的明細列。每個欄位都必須在自身上宣告選項;每個值必須是其中之一,且只列一次。這裡列出的欄位或選項,在從此對應表中移除之前不能刪除或變更類型。" + }, activityMilestones: { label: "活動里程碑", helpText: "由欄位到達某個值觸發的時間軸條目(ADR-0052 §5b.2):當一次更新把被監視的欄位變為該值時,稽核外掛會把該里程碑的摘要寫入記錄的活動時間軸,代替欄位變更條目。第一個比對的里程碑生效。" diff --git a/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts new file mode 100644 index 00000000000..bf50f446ff0 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-closed-states-37766.integration.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7; #37766 N45, ruling 7253749311 option D] The + * opening conditions at the real metadata door, from the shared author-time + * rule `validateApprovalClosedStates` (`@objectstack/lint`): an active save of + * a flow or an object where an approval could not show itself in progress on + * a closing field is refused; a draft is not, its promotion is; and a package + * publish is judged as the batch leaves it live (S3 of the review of #38527, + * confirmed here: the door's pending declarations already carry the batch). + * The approvals plugin adds no gate of its own. + * + * Real kernel, real ObjectQL engine and metadata protocol, real automation + * engine, the real approvals plugin, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin } from '@objectstack/service-automation'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; + +const text = (name: string) => ({ name, type: 'text' as const }); +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); + +/** Two steps on `object`'s approval field, with a timer between them where `hold`: D5 condition 5. */ +function approvalFlow(name: string, object: string, hold: boolean) { + const nodes: any[] = [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: object, triggerType: 'record-after-update' } }, + step('first', 'approver'), + ...(hold ? [{ id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }] : []), + step('second', 'approver2'), + { id: 'end', type: 'end', label: 'End' }, + ]; + const afterFirst = hold ? 'hold' : 'second'; + return { + name, label: name, type: 'autolaunched', + nodes, + edges: [ + { id: 'e0', source: 'start', target: 'first' }, + { id: 'e1a', source: 'first', target: afterFirst, label: 'approve' }, + { id: 'e1r', source: 'first', target: 'end', label: 'reject' }, + ...(hold ? [{ id: 'e2', source: 'hold', target: 'second' }] : []), + { id: 'e3a', source: 'second', target: 'end', label: 'approve' }, + { id: 'e3r', source: 'second', target: 'end', label: 'reject' }, + ], + }; +} + +describe('[ADR-0162 item 7, N45 as ruled] the opening conditions at the metadata door', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let protocol: any; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot() { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.use(new ApprovalsServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + protocol = kernel.getService('protocol'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + (ql.registry as any).installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'crm' }, 'authored'); + await ql.syncSchemas(); + } + + /** An authored package the saves go into, as `POST /packages` installs one. */ + const PKG = 'app.crm'; + const authored = { name: 'crm_note', label: 'Note', sharingModel: 'private', fields }; + const closing = { ...authored, closedStates: { approval_status: ['approved', 'rejected'] } }; + const flowRows = async (name: string) => + (await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]; + const refusalText = (err: any) => JSON.stringify({ message: err?.message, issues: err?.issues ?? err?.details }); + + it('refuses an active flow save whose approval holds a pause between two steps on a closing field', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG, + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + // The door's existing authoring refusal: no new error code (S4 of the review of #38527 falls away). + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(refusalText(err)).toContain('approval-closed-state-gap'); + expect(refusalText(err)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + expect((await flowRows('note_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('lets an active flow save through that meets every condition', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const out = await protocol.saveMetaItem({ type: 'flow', name: 'note_ok', item: approvalFlow('note_ok', 'crm_note', false), packageId: PKG }); + expect(out.success).toBe(true); + }); + + it('does not refuse a draft, and refuses its promotion', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG })).success).toBe(true); + const saved = await protocol.saveMetaItem({ + type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG, mode: 'draft', + }); + expect(saved.success).toBe(true); + const err = await protocol.publishMetaItem({ type: 'flow', name: 'note_wait', packageId: PKG }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(refusalText(err)).toContain('approval-closed-state-gap'); + expect((await flowRows('note_wait')).filter((r) => r.state === 'active')).toEqual([]); + }); + + it('refuses an object save that starts to close on the field of a live approval that pauses between two steps', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + const err = await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(refusalText(err)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); + + it('judges a package publish as it will be live: the closing object and the flow it repairs, in one batch', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG, mode: 'draft' }); + await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', false), packageId: PKG, mode: 'draft' }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.failed ?? []).toEqual([]); + expect(out.success).toBe(true); + }); + + it('refuses a package publish whose object starts to close while the batch leaves the live flow pausing', async () => { + await boot(); + expect((await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: authored, packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'flow', name: 'note_wait', item: approvalFlow('note_wait', 'crm_note', true), packageId: PKG })).success).toBe(true); + await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: closing, packageId: PKG, mode: 'draft' }); + const out = await protocol.publishPackageDrafts({ packageId: PKG }); + expect(out.success).toBe(false); + expect(JSON.stringify(out.failed)).toContain('Node hold (wait) of flow note_wait can pause the run between two approval steps of crm_note'); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts b/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts new file mode 100644 index 00000000000..fc1ee43d092 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-closed-states-sentences.test.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5] The author and the first request read the same sentence for a + * gap: the authoring rule's catalog (`@objectstack/lint`, + * `validate-approval-closed-states.user-text.ts`) holds a copy of this + * plugin's `approvalOpening*` sentences, and this test holds the two equal, + * kind by kind and locale by locale. + */ + +import { describe, expect, it } from 'vitest'; +import { APPROVAL_CLOSED_STATE_GAP, findingUserMessage } from '@objectstack/lint'; +import { approvalMessages } from './translations/messages.js'; + +/** Each gap kind the authoring rule reports, and the first request's message id for it. */ +const KIND_TO_ID = { + no_pending_option: 'approvalOpeningNoPendingOption', + closes_in_flight: 'approvalOpeningClosesInFlight', + state_machine_no_pending: 'approvalOpeningStateMachine', + readonly_when: 'approvalOpeningReadonlyWhen', + option_visible_when: 'approvalOpeningOptionVisibleWhen', + other_field: 'approvalOpeningOtherField', + no_field: 'approvalOpeningNoField', + pause_between_steps: 'approvalOpeningPause', + map_with_approval: 'approvalOpeningMapApproval', +} as const; + +/** The platform locale tag the rule's catalog uses, and the plugin's pack for it. */ +const LOCALES = { + en: 'en', 'zh-Hans': 'zh-CN', 'zh-Hant': 'zh-Hant', es: 'es-ES', ar: 'ar', fr: 'fr', + 'pt-BR': 'pt-BR', ru: 'ru', de: 'de', ja: 'ja-JP', ko: 'ko', +} as const; + +const HOLES = ['field', 'object', 'step', 'flow', 'value', 'rule', 'other', 'node', 'type']; + +describe('the authoring rule and the first request: one sentence per gap', () => { + for (const [tag, pack] of Object.entries(LOCALES)) { + it(`agrees in ${tag}`, () => { + for (const [kind, id] of Object.entries(KIND_TO_ID)) { + // Each hole rendered as its own spelling, so the two templates compare as written. + const params: Record = { kind }; + for (const h of HOLES) params[h] = `{{${h}}}`; + const authored = findingUserMessage({ rule: APPROVAL_CLOSED_STATE_GAP, userTextParams: params }, [tag]); + expect([kind, authored]).toEqual([kind, (approvalMessages[pack] as Record)[id]]); + } + }); + } +}); diff --git a/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts new file mode 100644 index 00000000000..5021f2a5e87 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-hold-37767.integration.test.ts @@ -0,0 +1,405 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5 "the hold", Execution item 8, #37767 piece 5] On an object that + * declares `closedStates`, a document is held for the whole of every approval: + * through each passage, from a step's decision until the next request opens + * or the approval is over, as well as while a request is pending. + * + * The pending lock reads the requests that carry the mark (`unjudged_since`) + * beside the pending ones, and holds the record and its `master_detail` lines + * as a pending request under a locking node does, whatever the node's + * `lockRecord`. It passes a system context, a write that carries only the + * mirror field, the revise window of a returned request, the record's own + * delete, and a write that carries a run of the approval, known by its root + * run (`flowRootRunId`, which the automation engine stamps on every write of + * a run beside `flowRunId`). + * + * Each passage is observed from inside it: a `mark` node between two steps + * (or after the last) runs the write under test while the passage lasts, + * either as a caller or as its own run, the way a data node writes + * (`resolveRunDataContext`). + * + * Real kernel, real ObjectQL engine, real automation engine, real approval + * node, the plugin's own lock hooks, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, resolveRunDataContext, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { bindApprovalLockHook, bindDetailRowLockHook, bindRecordDeleteCancelHook } from './lifecycle-hooks.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, tenantId: ORG, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes only on a value of its own, on another field than the approval's. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, held as on `main`. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; +/** Declares no closed state when its approval opens; the test declares one afterwards. */ +const late = { name: 'crm_late', label: 'Late', fields }; +const lateClosing = { ...late, closedStates: { stage: ['done'] } }; +/** A line of the invoice. */ +const invoiceLine = { + name: 'crm_invoice_line', label: 'Invoice Line', + fields: { name: text('name'), invoice: { name: 'invoice', type: 'master_detail' as const, reference: 'crm_invoice' } }, +}; +/** A product whose delete cascades into the invoice's bundle lines. */ +const product = { name: 'crm_product', label: 'Product', fields: { name: text('name') } }; +const bundleLine = { + name: 'crm_bundle_line', label: 'Bundle Line', + fields: { + name: text('name'), + invoice: { name: 'invoice', type: 'master_detail' as const, reference: 'crm_invoice' }, + product: { name: 'product', type: 'lookup' as const, reference: 'crm_product', deleteBehavior: 'cascade' as const }, + }, +}; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const probe = { id: 'probe', type: 'mark', label: 'Probe' }; +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[]) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges }); +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + // A probe between the two steps. + flow('two_probe', [step('first', 'approver'), probe, step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), + // The same, under a node that leaves the record open while its request is pending. + flow('unlocked_probe', [step('first', 'approver', { lockRecord: false }), probe, step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), + // A probe after the only step. + flow('only_probe', [step('only', 'approver'), probe], + [edge('start', 'only'), ...decided('only', 'probe'), edge('probe', 'end')]), + // Two levels of runs: the root delegates to a middle run, which delegates the + // first step and then probes, as the middle run, after the child's decision. + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + flow('mid_probe', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }, probe], + [edge('start', 'inner'), edge('inner', 'probe'), edge('probe', 'end')]), + flow('root_mid_probe', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'mid_probe' } }, step('second', 'approver2')], + [edge('start', 'mid'), edge('mid', 'second'), ...decided('second', 'end')]), + // Two steps, the second of which can be sent back for revision. + flow('two_revise', [step('first', 'approver'), step('second', 'approver2'), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'end', 'approve'), edge('second', 'end', 'reject'), + edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), +]; + +describe('[ADR-0162 D5, item 8] the hold: a document is held through every passage of its approval', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** What runs while the `probe` node executes: inside the passage that reached it, with the run's context. */ + let during: ((context: any) => Promise) | undefined; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + during = undefined; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, ticket, memo, late, invoiceLine, product, bundleLine, + SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async () => {} } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + bindApprovalLockHook(ql as any, quiet as any); + bindDetailRowLockHook(ql as any, quiet as any); + bindRecordDeleteCancelHook(ql as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (node.id === 'probe') await during?.(context); + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T, code: undefined as string | undefined }), (e: any) => ({ ok: undefined, code: String(e?.code ?? e?.message ?? e) })); + /** A caller's edit of the record: no run behind it. */ + const callerEdit = (object: string, id: string, stage = 'edited by a caller') => + settle(ql.update(object, { id, stage }, { context: asPerson('owner') })); + /** A write by the run whose node is executing, as a data node makes it. */ + const runEdit = (context: any, object: string, id: string, stage = 'edited by the run') => + settle(ql.update(object, { id, stage }, { context: resolveRunDataContext(context) as any })); + /** Run `fn` with no door judging: the shape a process that died after the door's own action leaves. */ + const withoutDoor = async (fn: () => Promise): Promise => { + const judge = (svc as any).judgeApprovalAfterDoor; + (svc as any).judgeApprovalAfterDoor = async () => 'undetermined'; + try { return await fn(); } finally { (svc as any).judgeApprovalAfterDoor = judge; } + }; + + describe('a caller is held through the passage', () => { + it('between two steps: a caller\'s edit is refused, the run\'s own write lands, and the field reads pending', async () => { + await start('two_probe', 'crm_invoice', 'i_between'); + const seen: unknown[] = []; + during = async (context) => { + seen.push(['caller', (await callerEdit('crm_invoice', 'i_between')).code]); + seen.push(['run', (await runEdit(context, 'crm_invoice', 'i_between')).code]); + seen.push(['field', (await read('crm_invoice', 'i_between')).approval_status]); + seen.push(['marks', await marks('i_between')]); + }; + await decide('i_between', 'approve', 'approver'); + expect(seen).toEqual([['caller', 'RECORD_LOCKED'], ['run', undefined], ['field', 'pending'], ['marks', [true]]]); + expect((await read('crm_invoice', 'i_between')).stage).toBe('edited by the run'); + expect((await requestsOn('i_between')).map((r) => r.status), 'the approval went on').toEqual(['approved', 'pending']); + }); + + it('after the last decision, until the approval is over: a caller\'s edit is refused', async () => { + await start('only_probe', 'crm_invoice', 'i_after'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_invoice', 'i_after')).code; }; + await decide('i_after', 'approve', 'approver'); + expect(caller).toBe('RECORD_LOCKED'); + expect((await read('crm_invoice', 'i_after')).approval_status, 'the outcome, once the approval is over').toBe('approved'); + expect(await marks('i_after')).toEqual([false]); + }); + + it('an approval whose field the object does not close on, on an object that closes only on a value of its own: held too', async () => { + await start('two_probe', 'crm_ticket', 't_between'); + const seen: unknown[] = []; + during = async () => { + seen.push((await callerEdit('crm_ticket', 't_between')).code); + seen.push((await read('crm_ticket', 't_between')).approval_status); + }; + await decide('t_between', 'approve', 'approver'); + expect(seen, 'held, and its outcome written at once').toEqual(['RECORD_LOCKED', 'approved']); + }); + + it('CONTROL: an object that declares no closed state is not held between two steps, as on main', async () => { + await start('two_probe', 'crm_memo', 'm_between'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_memo', 'm_between')).code; }; + await decide('m_between', 'approve', 'approver'); + expect(caller).toBeUndefined(); + expect((await read('crm_memo', 'm_between')).stage).toBe('edited by a caller'); + }); + + it('a write that carries only the mirror field passes, as it does while a request is pending', async () => { + await start('two_probe', 'crm_ticket', 't_mirror'); + // A writer that stamps no `updated_by`: the only shape whose write + // carries the mirror field alone (a person's write carries `updated_by` + // as well, and is refused in both states). + const unattributed = { tenantId: ORG, positions: [], permissions: [] } as any; + const mirrorWrite = (ctx: any, value: string) => + settle(ql.update('crm_ticket', { id: 't_mirror', approval_status: value }, { context: ctx })); + const pending = [(await mirrorWrite(unattributed, 'pending')).code, (await mirrorWrite(asPerson('owner'), 'pending')).code]; + let passage: unknown[] = []; + during = async () => { passage = [(await mirrorWrite(unattributed, 'pending')).code, (await mirrorWrite(asPerson('owner'), 'pending')).code]; }; + await decide('t_mirror', 'approve', 'approver'); + expect(pending).toEqual([undefined, 'RECORD_LOCKED']); + expect(passage).toEqual(pending); + }); + + it('a node that declares lockRecord: false: a caller\'s edit lands while its request is pending, and is refused after its decision', async () => { + await start('unlocked_probe', 'crm_invoice', 'i_unlocked'); + expect((await callerEdit('crm_invoice', 'i_unlocked', 'while pending')).code).toBeUndefined(); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_invoice', 'i_unlocked')).code; }; + await decide('i_unlocked', 'approve', 'approver'); + expect(caller).toBe('RECORD_LOCKED'); + }); + + it('a line of the record: a caller\'s line write is refused in the passage, and the run\'s lands', async () => { + await start('two_probe', 'crm_invoice', 'i_lines'); + const seen: unknown[] = []; + during = async (context) => { + seen.push((await settle(ql.insert('crm_invoice_line', { id: 'l_caller', name: 'x', invoice: 'i_lines', organization_id: ORG }, { context: asPerson('owner') }))).code); + seen.push((await settle(ql.insert('crm_invoice_line', { id: 'l_run', name: 'y', invoice: 'i_lines', organization_id: ORG }, { context: resolveRunDataContext(context) as any }))).code); + }; + await decide('i_lines', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await ql.find('crm_invoice_line', { where: { invoice: 'i_lines' }, context: SYS })).map((l: any) => l.id)).toEqual(['l_run']); + }); + }); + + describe('the approval\'s own runs pass, known by their root run', () => { + it('a node of a middle run, after the step its child decided: its write lands, and a caller\'s is refused', async () => { + await start('root_mid_probe', 'crm_invoice', 'i_mid'); + const seen: unknown[] = []; + let runs: { run?: string; root?: string } = {}; + during = async (context) => { + const data = resolveRunDataContext(context) as any; + runs = { run: data.flowRunId, root: data.flowRootRunId }; + seen.push(['run', (await runEdit(context, 'crm_invoice', 'i_mid')).code]); + seen.push(['caller', (await callerEdit('crm_invoice', 'i_mid')).code]); + // The same run's write without the root run it carries: the run is + // none the request names, so only the root run lets it through. + seen.push(['run without its root', (await settle(ql.update('crm_invoice', { id: 'i_mid', stage: 'x' }, { context: { ...data, flowRootRunId: undefined } }))).code]); + }; + await decide('i_mid', 'approve', 'approver'); + const [first] = await requestsOn('i_mid'); + expect(runs.root, 'the write carries the root run the request records').toBe(String(first.root_run_id)); + expect([first.flow_run_id, first.root_run_id, first.record_run_id].map(String), 'the middle run is none the request names').not.toContain(runs.run); + expect(seen).toEqual([['run', undefined], ['caller', 'RECORD_LOCKED'], ['run without its root', 'RECORD_LOCKED']]); + expect((await requestsOn('i_mid')).map((r) => r.status), 'the approval went on to its second step').toEqual(['approved', 'pending']); + }); + + it('a hook\'s write-back carries the run where the hook writes through its own api, and is refused where it writes outside it', async () => { + await start('two_probe', 'crm_invoice', 'i_hook'); + ql.registerHook('afterUpdate', async (ctx: any) => { + const stage = ctx?.input?.data?.stage; + if (stage === 'through the api') await ctx.api.object('crm_invoice').update({ id: 'i_hook', name: 'written back' }); + if (stage === 'outside the run') await ql.update('crm_invoice', { id: 'i_hook', name: 'written back' }, { context: asPerson('owner') }); + }, { object: 'crm_invoice', packageId: 'hold-test-hook' } as any); + const seen: unknown[] = []; + during = async (context) => { + seen.push((await runEdit(context, 'crm_invoice', 'i_hook', 'outside the run')).code); + seen.push((await runEdit(context, 'crm_invoice', 'i_hook', 'through the api')).code); + }; + await decide('i_hook', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await read('crm_invoice', 'i_hook')).name).toBe('written back'); + }); + + it('a cascade into a line: a caller\'s delete of the other master is refused, and the run\'s lands', async () => { + await start('two_probe', 'crm_invoice', 'i_cascade'); + for (const id of ['p_caller', 'p_run']) await ql.insert('crm_product', { id, name: id, organization_id: ORG }, { context: SYS }); + for (const p of ['p_caller', 'p_run']) { + await ql.insert('crm_bundle_line', { id: `b_${p}`, name: p, invoice: 'i_cascade', product: p, organization_id: ORG }, { context: SYS }); + } + const seen: unknown[] = []; + during = async (context) => { + seen.push((await settle(ql.delete('crm_product', { where: { id: 'p_caller' }, context: asPerson('owner') } as any))).code); + seen.push((await settle(ql.delete('crm_product', { where: { id: 'p_run' }, context: resolveRunDataContext(context) } as any))).code); + }; + await decide('i_cascade', 'approve', 'approver'); + expect(seen).toEqual(['RECORD_LOCKED', undefined]); + expect((await ql.find('crm_bundle_line', { where: { invoice: 'i_cascade' }, context: SYS })).map((l: any) => l.id)).toEqual(['b_p_caller']); + }); + }); + + describe('what the hold keeps of the pending lock', () => { + it('the revise window that follows an earlier step\'s decision is open to every caller who may edit, a mark left behind included', async () => { + await start('two_revise', 'crm_invoice', 'i_revise'); + await decide('i_revise', 'approve', 'approver'); + const [first, second] = await requestsOn('i_revise'); + await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect((await requestsOn('i_revise')).map((r) => r.status)).toEqual(['approved', 'returned']); + // A mark the opening of the second request did not clear. + await ql.update('sys_approval_request', { id: first.id, unjudged_since: new Date().toISOString() }, { context: SYS }); + expect((await callerEdit('crm_invoice', 'i_revise')).code).toBeUndefined(); + }); + + it('a caller\'s delete in a passage lands and ends the approval: marked abandoned, its marks cleared, nothing written', async () => { + await start('only_probe', 'crm_invoice', 'i_delete'); + let deleted: string | undefined = 'not reached'; + during = async () => { deleted = (await settle(ql.delete('crm_invoice', { where: { id: 'i_delete' }, context: asPerson('owner') } as any))).code; }; + await settle(decide('i_delete', 'approve', 'approver')); + expect(deleted).toBeUndefined(); + expect(await read('crm_invoice', 'i_delete')).toBeUndefined(); + const [only] = await requestsOn('i_delete'); + expect(only.status).toBe('approved'); + expect(only.unjudged_since).toBeNull(); + expect(JSON.parse(only.node_config_json).__abandoned?.reason).toBe('the record was deleted.'); + expect((await svc.reconcileMarkedApprovals()).scanned, 'the reconciler has nothing to try again').toBe(0); + }); + + it('the approvals-family read answers for a pending request only, as published: not locked in a passage', async () => { + await start('two_probe', 'crm_invoice', 'i_read'); + let answer: unknown; + during = async () => { answer = await svc.getRecordLock('crm_invoice', 'i_read', asPerson('owner')); }; + await decide('i_read', 'approve', 'approver'); + expect(answer).toEqual({ locked: false }); + expect(await svc.getRecordLock('crm_invoice', 'i_read', asPerson('owner')), 'its next request pending').toEqual({ locked: true, lockSource: 'record' }); + }); + + it('an approval that opened before the object declared closedStates is not held', async () => { + await start('two_probe', 'crm_late', 'x_late'); + ql.registry.registerObject(lateClosing as any, 'approvals-test', 'approvals-test'); + let caller: string | undefined = 'not reached'; + during = async () => { caller = (await callerEdit('crm_late', 'x_late')).code; }; + await decide('x_late', 'approve', 'approver'); + expect(await marks('x_late')).toEqual([false, false]); + expect(caller).toBeUndefined(); + }); + + it('a process that dies in a passage leaves the document held, and the reconciler ends the hold', async () => { + await start('two_step', 'crm_ticket', 't_died'); + await decide('t_died', 'approve', 'approver'); + await withoutDoor(() => decide('t_died', 'approve', 'approver2')); + expect(await marks('t_died')).toEqual([false, true]); + expect((await callerEdit('crm_ticket', 't_died')).code, 'held while nobody judged the approval').toBe('RECORD_LOCKED'); + + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await marks('t_died')).toEqual([false, false]); + expect((await callerEdit('crm_ticket', 't_died')).code, 'the hold ended with the judgement').toBeUndefined(); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts b/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts new file mode 100644 index 00000000000..a2b8a98a31b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts @@ -0,0 +1,364 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 8] What a multi-step approval leaves on its status + * mirror when it does not finish — measured as the code stands, before the + * outcome is held back on a field the object closes on. + * + * The item's design note (ruling record 7210179412 on its card) was read, not + * run, and its first build step is to pin four of its readings with tests. + * This file is that step. Each test records the value the mirror field keeps, + * which is what the later pieces of the item change on an object that declares + * `closedStates`; the object here declares none, so every assertion below is + * also the control those pieces keep: an object with no closed state behaves + * as it does today. + * + * - Reading 3: the door that records a decision is told about a parent run + * only where that parent STRANDED. A parent that was cancelled answers + * `RUN_NOT_FOUND` to the up-bubble, which is a `warn` line, and the door + * reports a clean resume with nothing behind it. + * - Reading 4: a node that fails after a decision ends the run `failed`; the + * engine answers `stranded`, and the door throws `RESUME_FAILED` with + * `repairable`. The decision stands, and no request is open. + * - Reading 5: a step that cannot open fails its node — `NO_APPROVERS` under + * `onEmptyApprovers: 'fail'`, `DUPLICATE_REQUEST` while another request is + * pending on the record. Unrouted, that is reading 4's strand; down a + * `fault` edge the run goes on and completes, with the step never asked. + * - Reading 6: `cancelRun` cancels one suspended run and touches no child. A + * parent parked at a `subflow` node is cancelled while its child's request + * is pending; the decision on the child is still admitted, the child + * completes, and the parent's next step is never asked. + * + * And reading 8 where it meets these: the dead-run sweep reads pending + * requests only, so after each of these ends it changes nothing. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as any; + +/** Records every level, so "only a warn line says so" is measurable. */ +function recordingLogger() { + const lines: Array<{ level: string; msg: string; meta?: unknown }> = []; + const mk = (level: string) => (msg: string, meta?: unknown) => { lines.push({ level, msg, meta }); }; + const self: any = { + lines, + info: mk('info'), warn: mk('warn'), error: mk('error'), debug: mk('debug'), + child() { return self; }, + }; + return self; +} + +function makeFakeEngine() { + const tables = new Map(); + const rows = (o: string) => (tables.get(o) ?? (tables.set(o, []), tables.get(o)!)); + const matches = (row: any, where: any) => Object.entries(where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`); + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); + if (v && typeof v === 'object' && '$ne' in (v as any)) return row[k] !== (v as any).$ne; + return row[k] === v; + }); + return { + tables, + async find(object: string, opts: any = {}) { + const where = opts.where ?? opts.filter ?? {}; + const out = rows(object).filter(r => matches(r, where)); + const start = opts.offset ?? 0; + const page = typeof opts.limit === 'number' ? out.slice(start, start + opts.limit) : out.slice(start); + return page.map(r => ({ ...r })); + }, + async insert(object: string, data: any) { rows(object).push({ ...data }); return { ...data }; }, + async update(object: string, data: any, options?: any) { + const dispatch = assertEngineUpdateDispatch(data, options); + const table = rows(object); + if (dispatch.kind === 'multi') { + let n = 0; + for (let i = 0; i < table.length; i++) { + if (matches(table[i], options?.where)) { table[i] = { ...table[i], ...data }; n++; } + } + return { updated: n }; + } + const i = table.findIndex(r => r.id === dispatch.id); + if (i >= 0) table[i] = { ...table[i], ...data }; + return i >= 0 ? { ...table[i] } : null; + }, + async delete(object: string, options?: any) { + const dispatch = assertEngineDeleteDispatch(options); + const table = rows(object); + if (dispatch.kind === 'multi') { + const survivors = table.filter(r => !matches(r, options?.where)); + const deleted = table.length - survivors.length; + table.splice(0, table.length, ...survivors); + return { deleted }; + } + const i = table.findIndex(r => r.id === dispatch.id); + if (i >= 0) table.splice(i, 1); + return { id: dispatch.id }; + }, + }; +} + +const MIRROR = 'approval_status'; +const approvalStep = (id: string, approvers: unknown[], extra: Record = {}) => ({ + id, type: 'approval', label: id, config: { approvers, approvalStatusField: MIRROR, ...extra }, +}); + +/** + * Two approval steps with a `mark` node between them. `step2` is the caller's, + * and `fault` adds a `fault` edge from it to the end. + */ +function twoStepFlow(step2: Record, opts: { fault?: boolean } = {}) { + return { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('step1', [{ type: 'user', value: 'u1' }]), + { id: 'between', type: 'mark', label: 'Between the steps' }, + step2, + { id: 'done', type: 'mark', label: 'Done' }, + { id: 'rejected', type: 'mark', label: 'Rejected' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'step1' }, + { id: 'e2', source: 'step1', target: 'between', label: 'approve' }, + { id: 'e3', source: 'step1', target: 'rejected', label: 'reject' }, + { id: 'e4', source: 'between', target: 'step2' }, + { id: 'e5', source: 'step2', target: 'done', label: 'approve' }, + { id: 'e6', source: 'step2', target: 'rejected', label: 'reject' }, + { id: 'e7', source: 'done', target: 'end' }, + { id: 'e8', source: 'rejected', target: 'end' }, + ...(opts.fault ? [{ id: 'f1', source: 'step2', target: 'end', type: 'fault' }] : []), + ], + }; +} + +/** Another approval of the same record: one step. */ +const OTHER_APPROVAL = { + name: 'other_approval', label: 'Other approval', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('other_step', [{ type: 'user', value: 'u9' }]), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'x1', source: 'start', target: 'other_step' }, + { id: 'x2', source: 'other_step', target: 'end' }, + ], +}; + +/** A one-step approval, hosted by {@link PARENT}'s `subflow` node. */ +const CHILD = { + name: 'child_approval', label: 'Child approval', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + approvalStep('child_step', [{ type: 'user', value: 'u1' }]), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'c1', source: 'start', target: 'child_step' }, + { id: 'c2', source: 'child_step', target: 'end', label: 'approve' }, + { id: 'c3', source: 'child_step', target: 'end', label: 'reject' }, + ], +}; + +/** The parent: its first step is the child's, its second its own. */ +const PARENT = { + name: 'parent_approval', label: 'Parent approval', type: 'autolaunched', + nodes: [ + { id: 'pstart', type: 'start', label: 'Start' }, + { id: 'sub', type: 'subflow', label: 'First step, in a child', config: { flowName: 'child_approval', outputVariable: 'subOut' } }, + approvalStep('parent_step', [{ type: 'user', value: 'u2' }]), + { id: 'pend', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'p1', source: 'pstart', target: 'sub' }, + { id: 'p2', source: 'sub', target: 'parent_step' }, + { id: 'p3', source: 'parent_step', target: 'pend' }, + ], +}; + +describe('[ADR-0162 item 8] an approval that does not finish, as the mirror stands today (readings 3–6)', () => { + let data: ReturnType; + let service: ApprovalService; + let logger: ReturnType; + let marks: string[]; + let throwOn: Record; + let onMark: Record Promise) | undefined>; + + beforeEach(() => { + marks = []; + throwOn = {}; + onMark = {}; + logger = recordingLogger(); + data = makeFakeEngine(); + data.tables.set('crm_deal', [{ id: 'd1', amount: 100, [MIRROR]: 'draft' }]); + data.tables.set('sys_user', ['submitter', 'u1', 'u2', 'u9'].map((id) => ({ id, email: `${id}@example.test` }))); + service = new ApprovalService({ engine: data as any, logger }); + }); + + function boot(...flows: Array>) { + const automation = new AutomationEngine(logger, new InMemorySuspendedRunStore()); + installBuiltinNodes(automation, { logger, getService() { throw new Error('none'); } } as any); + registerApprovalNode(automation, service, logger); + automation.registerNodeExecutor({ + type: 'mark', + async execute(node: any) { + const boom = throwOn[node.id]; + if (boom) throw new Error(boom); + await onMark[node.id]?.(); + marks.push(node.id); + return { success: true }; + }, + } as never); + for (const flow of flows) automation.registerFlow(flow.name, flow as never); + service.attachAutomation(automation); + return automation; + } + + const submit = async (automation: AutomationEngine, flow: string) => + (await automation.execute(flow, { object: 'crm_deal', record: { id: 'd1', amount: 100 }, userId: 'submitter' } as never)) as any; + const mirrorField = () => data.tables.get('crm_deal')![0][MIRROR]; + const requests = async () => + (await data.find('sys_approval_request', {})).map((r: any) => ({ step: r.flow_node_id, status: r.status })); + const firstPending = async () => (await data.find('sys_approval_request', { where: { status: 'pending' } }))[0]; + const stepLog = async (automation: AutomationEngine, runId: string) => + ((await automation.getRun(runId)) as any)?.steps?.map((s: any) => [s.nodeId, s.status]) ?? []; + const approveFirst = async () => { + const req = await firstPending(); + return service + .decide(req.id, { decision: 'approve', actorId: 'u1' }, SYSTEM_CTX) + .then((r) => ({ ok: true as const, r }), (e: Error) => ({ ok: false as const, e })); + }; + /** Reading 8: the dead-run sweep reads pending requests only, so here it changes nothing. */ + const sweepChangesNothing = async () => { + const before = { field: mirrorField(), requests: await requests() }; + await service.releaseDeadRunRequests(); + expect({ field: mirrorField(), requests: await requests() }, 'the sweep reads pending requests only').toEqual(before); + }; + + it('reading 4: a node that fails after a decision strands the run; the decision stands and the field keeps `approved`', async () => { + throwOn.between = 'the node between the steps failed'; + const automation = boot(twoStepFlow(approvalStep('step2', [{ type: 'user', value: 'u2' }]))); + const run = await submit(automation, 'two_step'); + expect(mirrorField()).toBe('pending'); + + const outcome = await approveFirst(); + + expect(outcome.ok, 'the decision door throws').toBe(false); + const err = outcome.ok ? (undefined as never) : outcome.e; + expect(err.message).toMatch(/^RESUME_FAILED/); + expect(strandedDecisionDetails(err)).toEqual({ finalized: true, decision: 'approve', runId: run.runId, repairable: true }); + expect((await automation.getRun(run.runId))?.status).toBe('failed'); + expect(await stepLog(automation, run.runId)).toEqual([['start', 'success'], ['step1', 'success'], ['between', 'failure']]); + expect(await requests(), 'the second step was never asked').toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + expect((await automation.restoreConsumedSuspension(run.runId, { requestedBy: 'ops' })).restored, 'an operator can put the pause back').toBe(true); + }); + + describe('reading 5: a later step that cannot open fails its node', () => { + const emptySlate = () => approvalStep('step2', [{ type: 'field', value: 'reviewer_id' }], { onEmptyApprovers: 'fail' }); + + it('on an empty slate under `fail`, unrouted: the run strands at the step, and the field keeps `approved`', async () => { + const automation = boot(twoStepFlow(emptySlate())); + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok).toBe(false); + const err = outcome.ok ? (undefined as never) : outcome.e; + expect(strandedDecisionDetails(err)).toEqual({ finalized: true, decision: 'approve', runId: run.runId, repairable: true }); + expect((await automation.getRun(run.runId))?.status).toBe('failed'); + const steps = ((await automation.getRun(run.runId)) as any).steps; + expect(steps.at(-1)).toMatchObject({ nodeId: 'step2', status: 'failure' }); + expect(steps.at(-1).error.message).toContain('NO_APPROVERS'); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); + + it('on an empty slate, down a `fault` edge to the end: the run completes with the step never asked, and the field keeps `approved`', async () => { + const automation = boot(twoStepFlow(emptySlate(), { fault: true })); + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok, 'the door answers a clean resume').toBe(true); + const answer = outcome.ok ? outcome.r : (undefined as never); + expect(answer.resumed).toBe(true); + expect(answer.resumeError).toBeUndefined(); + expect(answer.resumeFailure).toBeUndefined(); + expect((await automation.getRun(run.runId))?.status).toBe('completed'); + expect(await stepLog(automation, run.runId), 'the failure is in the step log, which is all that says so') + .toEqual([['start', 'success'], ['step1', 'success'], ['between', 'success'], ['step2', 'failure']]); + expect(marks, 'neither the approved nor the rejected branch ran').toEqual(['between']); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); + + for (const fault of [false, true]) { + it(`while another approval's request is pending on the record${fault ? ', down a `fault` edge' : ', unrouted'}: the field keeps that approval's \`pending\``, async () => { + const automation = boot(twoStepFlow(approvalStep('step2', [{ type: 'user', value: 'u2' }]), { fault }), OTHER_APPROVAL); + // Between the two steps, another approval of the same record opens: + // the first step's request is no longer pending, so nothing stops it. + onMark.between = async () => { + expect((await submit(automation, 'other_approval')).status).toBe('paused'); + }; + const run = await submit(automation, 'two_step'); + + const outcome = await approveFirst(); + + expect(outcome.ok).toBe(fault); + expect((await automation.getRun(run.runId))?.status).toBe(fault ? 'completed' : 'failed'); + const steps = ((await automation.getRun(run.runId)) as any).steps; + expect(steps.at(-1)).toMatchObject({ nodeId: 'step2', status: 'failure' }); + expect(steps.at(-1).error.message).toContain('DUPLICATE_REQUEST'); + expect(await requests()).toEqual([{ step: 'step1', status: 'approved' }, { step: 'other_step', status: 'pending' }]); + expect(mirrorField(), "the value the field keeps: the other approval's").toBe('pending'); + }); + } + }); + + it('readings 3 and 6: a parent cancelled above a pending child; the decision is admitted, the door reports a clean resume, and the field keeps `approved`', async () => { + const automation = boot(CHILD, PARENT); + const parent = await submit(automation, 'parent_approval'); + expect(parent.status, 'the parent parks at its subflow node').toBe('paused'); + const req = await firstPending(); + const childRunId = String(req.flow_run_id); + expect(childRunId, 'the request names the child run').not.toBe(parent.runId); + expect(req.root_run_id, "the request's approval is the parent's run").toBe(parent.runId); + expect(mirrorField()).toBe('pending'); + + // Reading 6: the cancel reaches the parent and touches no child. + expect(await automation.cancelRun(parent.runId, 'operator')).toBe(true); + expect((await automation.getRun(parent.runId))?.status).toBe('cancelled'); + expect(await automation.hasSuspendedRun(childRunId), 'the child is still parked').toBe(true); + expect((await firstPending())?.id, "the child's request is still pending").toBe(req.id); + + const outcome = await approveFirst(); + + // Reading 3: the decision is admitted, because the liveness check asks + // about the request's own run, and the door is told nothing of the parent. + expect(outcome.ok).toBe(true); + const answer = outcome.ok ? outcome.r : (undefined as never); + expect(answer.finalized).toBe(true); + expect(answer.resumed).toBe(true); + expect(answer.resumeError).toBeUndefined(); + expect(answer.resumeFailure, 'only a stranded parent is told to the door').toBeUndefined(); + expect((await automation.getRun(childRunId))?.status).toBe('completed'); + expect((await automation.getRun(parent.runId))?.status).toBe('cancelled'); + const bubble = logger.lines.filter((l: any) => String(l.msg).includes(`resuming parent '${parent.runId}' failed`)); + expect(bubble.map((l: any) => l.level), 'one warn line is all that says so').toEqual(['warn']); + expect(logger.lines.filter((l: any) => l.level === 'error')).toEqual([]); + expect(await requests(), "the parent's step was never asked").toEqual([{ step: 'child_step', status: 'approved' }]); + expect(mirrorField(), 'the value the field keeps').toBe('approved'); + await sweepChangesNothing(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index bc93e658922..4a0ea9a5f43 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -243,6 +243,8 @@ export function registerApprovalNode( runRoot: !hasParentRun(context), rootRun, recordRun, + // [ADR-0162 Execution item 7] A refused opening is worded in the run's locale. + locale: typeof context?.locale === 'string' ? context.locale : undefined, }, { ...SYSTEM_CTX, userId: context?.userId, diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts new file mode 100644 index 00000000000..f298162934b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts @@ -0,0 +1,260 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The check when an + * approval opens, as the service runs it at a request's opening: placed by + * the request's root run, judged once at the approval's first request, its + * between-two-steps set stamped on every request of an approval that touches + * an object declaring `closedStates`, and a refusal that names what is + * missing, in the run's locale. The read of the definition itself, arm by + * arm, is pinned over fixtures in `approval-opening-check.test.ts`. + * + * Real kernel, real ObjectQL engine, real automation engine (which hands the + * root run, slice A), real approval node, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, other_status: { ...statusField, name: 'other_status' } }; +/** Closes on its approval's outcome, and meets every condition of D5. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** The same object, declaring no closed state. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, field = 'approval_status') => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: field }, +}); +const endEdges = (from: string, to: string, n: number) => [ + { id: `e${n}a`, source: from, target: to, label: 'approve' }, + { id: `e${n}r`, source: from, target: 'end', label: 'reject' }, +]; + +/** Two steps on the same field: opens. */ +const twoStep = { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; +/** A timer between the two steps: D5 condition 5. */ +const waitBetween = { + name: 'wait_between', label: 'Wait between', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, + step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'hold', 2), { id: 'e3', source: 'hold', target: 'second' }, ...endEdges('second', 'end', 4)], +}; +/** The second step mirrors onto another field: D5 condition 4. */ +const otherField = { + name: 'other_field', label: 'Other field', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2', 'other_status'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; + +describe('[ADR-0162 item 7] the check when an approval opens', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot(opts: { sweeps?: boolean; invoiceDef?: Record; warns?: string[] } = {}) { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [opts.invoiceDef ?? invoice, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + const sink = opts.warns; + const serviceLogger = sink ? { ...quiet, warn: (message: string) => { sink.push(message); } } : quiet; + svc = new ApprovalService({ engine: ql, logger: serviceLogger as any }); + if (opts.sweeps !== false) svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + for (const flow of [twoStep, waitBetween, otherField]) automation.registerFlow(flow.name, flow as any); + } + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (flow: string, object: string, id: string, extra: Record = {}) => + automation.execute(flow, { object, record: await read(object, id), userId: 'owner', ...extra } as any) as Promise; + const approve = async (requestId: string, who: string) => + svc.decide(requestId, { decision: 'approve', actorId: who } as any, asPerson(who)); + + describe('an approval that meets every condition', () => { + beforeEach(() => boot()); + + it('opens, and each of its requests carries the set its first request was stamped with', async () => { + await seed('crm_invoice', 'i_ok'); + expect((await start('two_step', 'crm_invoice', 'i_ok')).status).toBe('paused'); + const [first] = await requestsOn('i_ok'); + expect(first.status).toBe('pending'); + const stamp = JSON.parse(first.between_steps_json); + expect(stamp).toEqual([{ flow: 'two_step', node: 'first' }]); + + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_ok'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json, 'a later request copies the first request\'s set').toBe(first.between_steps_json); + }); + + it('stamps nothing on an approval whose object declares no closed state', async () => { + await seed('crm_memo', 'm_ok'); + expect((await start('wait_between', 'crm_memo', 'm_ok')).status).toBe('paused'); + const [row] = await requestsOn('m_ok'); + expect(row.status).toBe('pending'); + expect(row.between_steps_json ?? null).toBeNull(); + }); + }); + + describe('an approval that misses a condition', () => { + beforeEach(() => boot()); + + it('does not open: the run fails with a sentence naming the flow, the step, the object and what is missing', async () => { + await seed('crm_invoice', 'i_wait'); + const out = await start('wait_between', 'crm_invoice', 'i_wait'); + expect(out.status).toBe('failed'); + const said = JSON.stringify(out); + expect(said).toContain('VALIDATION_FAILED'); + expect(said).toContain('Node hold (wait) of flow wait_between can pause the run between two approval steps of crm_invoice'); + expect(await requestsOn('i_wait'), 'no request opened').toEqual([]); + }); + + it('words the refusal in the run\'s locale', async () => { + await seed('crm_invoice', 'i_zh'); + const out = await start('other_field', 'crm_invoice', 'i_zh', { locale: 'zh-CN' }); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('流程 other_field 的步骤 second 可以作用于 crm_invoice,却把状态写到字段 other_status'); + }); + + }); + + it('does not judge a later request whose approval\'s earlier requests record no root run', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_unplaced'); + expect((await start('other_field', 'crm_invoice', 'i_unplaced')).status).toBe('paused'); + const [first] = await requestsOn('i_unplaced'); + // The shape of a request opened before requests recorded their root run. + await ql.update('sys_approval_request', { id: first.id, root_run_id: null, root_run_started_at: null, record_run_id: null }, { context: SYS }); + expect((await requestsOn('i_unplaced'))[0].root_run_id ?? null).toBeNull(); + + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_unplaced'); + // Judged, the second step's other field would refuse it; it cannot be placed, so it opens. + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('does not judge again a later request of an approval opened before the object declared closedStates', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_before'); + expect((await start('other_field', 'crm_invoice', 'i_before')).status).toBe('paused'); + const [first] = await requestsOn('i_before'); + expect(first.between_steps_json ?? null).toBeNull(); + + // The object now declares the key, as after an upgrade. + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_before'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('refuses the first request on a host that runs no job service', async () => { + await boot({ sweeps: false }); + await seed('crm_invoice', 'i_host'); + const out = await start('two_step', 'crm_invoice', 'i_host'); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('crm_invoice declares closedStates, and this host runs no job service'); + expect(await requestsOn('i_host')).toEqual([]); + + // An approval whose objects declare no closed state opens on that host. + await seed('crm_memo', 'm_host'); + expect((await start('two_step', 'crm_memo', 'm_host')).status).toBe('paused'); + }); + + describe('the log line at a refusal says the object closes on its approval field only where a gap is about it', () => { + const FIELD_CLAIM = 'closes on its approval field'; + const refusalWarns = (warns: string[]) => warns.filter((w) => w.includes('was refused at its first request')); + + it('does not say it where the host\'s gap is the only one', async () => { + const warns: string[] = []; + await boot({ sweeps: false, warns }); + await seed('crm_invoice', 'i_host_log'); + expect((await start('two_step', 'crm_invoice', 'i_host_log')).status).toBe('failed'); + const logged = refusalWarns(warns); + expect(logged).toHaveLength(1); + expect(logged[0]).not.toContain(FIELD_CLAIM); + expect(logged[0]).toContain('declares closedStates'); + }); + + it('says it where a gap is about the field (control)', async () => { + const warns: string[] = []; + await boot({ warns }); + await seed('crm_invoice', 'i_wait_log'); + expect((await start('wait_between', 'crm_invoice', 'i_wait_log')).status).toBe('failed'); + const logged = refusalWarns(warns); + expect(logged).toHaveLength(1); + expect(logged[0]).toContain(FIELD_CLAIM); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts new file mode 100644 index 00000000000..0a5a830b5e0 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts @@ -0,0 +1,337 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The read of an + * approval's whole definition at its first request, over fixtures: each D5 + * condition as revised on 2026-11-27, the between-two-steps set it stamps, the + * unread parts, and the host's `job` service. The service's wiring (root run, + * later requests, the refusal and its locale) is pinned in + * `approval-opening-check-37766.integration.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { + judgeApprovalOpening, + type OpeningCheckSource, + type OpeningFlowBody, + type OpeningFlowNode, + type OpeningGap, +} from './approval-opening-check.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; + +function statusField(extra: Record = {}, options: unknown[] = STATUSES.map((v) => ({ value: v, label: v }))) { + return { type: 'select', options, ...extra }; +} + +/** An object that closes on `approved` and `rejected` of `status`, and meets every condition. */ +function invoice(over: Record = {}) { + return { name: 'invoice', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField() }, ...over }; +} + +const memo = { name: 'memo', fields: { status: statusField() } }; + +const DESCRIPTORS: Record = { + wait: { supportsPause: true }, + screen: { supportsPause: true }, + approval: { supportsPause: true }, + decision: {}, + assignment: {}, + update_record: {}, + create_record: {}, + loop: {}, + parallel: {}, + try_catch: {}, +}; + +function source(spec: { + objects?: Record; + flows?: Record; + descriptors?: Record; + host?: boolean; +}): OpeningCheckSource & { read: string[] } { + const objects = spec.objects ?? { invoice: invoice(), memo }; + const descriptors = { ...DESCRIPTORS, ...spec.descriptors }; + const read: string[] = []; + return { + read, + objectSchema: (name) => { read.push(name); return objects[name]; }, + calleeFlow: async (name) => (spec.flows?.[name] ? { key: name, body: spec.flows[name]! } : null), + nodeDescriptor: (type) => descriptors[type], + hostRunsReconciler: spec.host ?? true, + }; +} + +const step = (id: string, field: string | null = 'status'): OpeningFlowNode => + ({ id, type: 'approval', config: field ? { approvalStatusField: field } : {} }); +const n = (id: string, type: string, config: Record = {}): OpeningFlowNode => ({ id, type, config }); + +/** A body whose nodes run one after another, wrapped in `start` and `end`. */ +function chain(...nodes: OpeningFlowNode[]): OpeningFlowBody { + const all = [n('start', 'start'), ...nodes, n('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} + +async function judge(root: OpeningFlowBody, opts: Parameters[0] & { rootObject?: string | null } = {}) { + const src = source(opts); + const rootObject = opts.rootObject === undefined ? 'invoice' : opts.rootObject; + const out = await judgeApprovalOpening({ rootFlow: { key: 'F', body: root }, rootFlowName: 'F', rootObject }, src); + return { ...out, read: src.read }; +} + +const kinds = (gaps: OpeningGap[]) => gaps.map((g) => g.kind); + +describe('the opening check: an approval that meets every condition', () => { + it('opens a two-step approval on a closing field, and stamps what stands between the steps', async () => { + const out = await judge(chain(step('a1'), n('d1', 'decision'), step('a2'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + // a1 (a step can follow it) and d1 (after a1, before a2); not a2, after which no step follows. + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd1' }]); + }); + + it('does not refuse a writing node in a run-as-user flow (the withdrawn writing-node condition)', async () => { + const root = { ...chain(step('a1'), n('w', 'update_record', { objectName: 'invoice', fields: { note: 'x' } }), step('a2')), runAs: 'user' }; + const out = await judge(root); + expect(out.gaps).toEqual([]); + expect(out.between).toContainEqual({ flow: 'F', node: 'w' }); + }); +}); + +describe('the opening check: D5 conditions 1 to 3, on the field', () => { + it('refuses a field that does not declare pending', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({}, ['draft', 'approved', 'rejected']) } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned'])('refuses an object that closes on %s', async (value) => { + const objects = { invoice: invoice({ closedStates: { status: ['approved', value] } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'closes_in_flight', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('refuses a state_machine rule whose moves out of a closed approved leave out pending', async () => { + const validations = [{ name: 'flow_of_status', type: 'state_machine', field: 'status', transitions: { approved: ['draft'], rejected: ['pending', 'draft'] } }]; + const out = await judge(chain(step('a1')), { objects: { invoice: invoice({ validations }) } }); + expect(out.gaps).toEqual([{ kind: 'state_machine_no_pending', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value: 'approved', rule: 'flow_of_status' }]); + }); + + it('reads a state_machine rule that keeps a closed value final as missing pending, and one that declares no move out of it as nothing', async () => { + const final = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { rejected: [] } }]; + expect(kinds((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: final }) } })).gaps)).toEqual(['state_machine_no_pending']); + const silent = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { draft: ['pending'] } }]; + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: silent }) } })).gaps).toEqual([]); + }); + + it('refuses a field that carries a readonlyWhen', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({ readonlyWhen: 'record.locked' }) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'readonly_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned', 'approved', 'rejected', 'recalled'])('refuses a visibleWhen on the %s option', async (value) => { + const options = STATUSES.map((v) => (v === value ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + const objects = { invoice: invoice({ fields: { status: statusField({}, options) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'option_visible_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('does not refuse a visibleWhen on an option that is no request status', async () => { + const options = STATUSES.map((v) => (v === 'draft' ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ fields: { status: statusField({}, options) } }) } })).gaps).toEqual([]); + }); + + it('reads nothing of an object that closes only on values of its own, also with a state_machine that keeps one final', async () => { + const validations = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { archived: [] } }]; + const objects = { invoice: invoice({ closedStates: { status: ['archived'] }, validations, fields: { status: statusField({ readonlyWhen: 'x' }) } }) }; + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2')), { objects }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between.length).toBeGreaterThan(0); + }); +}); + +describe('the opening check: D5 condition 4, every step mirrors onto the field', () => { + it.each([ + ['after', [step('a1'), step('a2', 'other_status')]], + ['ahead of', [step('a2', 'other_status'), step('a1')]], + ] as const)('refuses a step %s a concerned step that mirrors onto another field', async (_where, nodes) => { + const out = await judge(chain(...nodes)); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status', other: 'other_status' }]); + }); + + it('refuses a step that names no field beside a concerned one', async () => { + const out = await judge(chain(step('a1'), step('a2', null))); + expect(out.gaps).toEqual([{ kind: 'no_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status' }]); + }); + + it('does not refuse, but stamps, an approval none of whose steps names a closing field', async () => { + const out = await judge(chain(step('a1', null), n('w', 'wait'), step('a2', 'other_status'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'w' }]); + }); + + it('refuses a step two levels down that mirrors onto another field', async () => { + const flows = { + S1: chain(n('s2', 'subflow', { flowName: 'S2' })), + S2: chain(step('deep', 'other_status')), + }; + const out = await judge(chain(step('a1'), n('s1', 'subflow', { flowName: 'S1' })), { flows }); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'S2', step: 'deep', object: 'invoice', field: 'status', other: 'other_status' }]); + }); +}); + +describe('the opening check: D5 condition 5, no pause between two steps', () => { + it.each(['wait', 'screen'])('refuses a %s between two steps', async (type) => { + const out = await judge(chain(step('a1'), n('p', type), step('a2'))); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'p', type, object: 'invoice' }]); + }); + + it.each(['wait', 'screen'])('refuses a %s between two steps in a screen flow too (a run with no record trigger)', async (type) => { + const root = { ...chain(step('a1'), n('p', type), step('a2')), type: 'screen' }; + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('does not refuse a pause before the first step or after the last', async () => { + expect((await judge(chain(n('p0', 'wait'), step('a1'), step('a2'), n('p1', 'screen')))).gaps).toEqual([]); + }); + + it('refuses a node type that publishes no descriptor, and one the engine cannot be asked about', async () => { + expect(kinds((await judge(chain(step('a1'), n('x', 'custom_thing'), step('a2')))).gaps)).toEqual(['pause_between_steps']); + const unread = await judge(chain(step('a1'), n('x', 'decision'), step('a2')), { descriptors: { decision: 'unread' } }); + expect(kinds(unread.gaps)).toEqual(['pause_between_steps']); + }); + + it('follows aliasOf to the canonical descriptor', async () => { + const descriptors = { hold: { aliasOf: 'wait' }, branch: { aliasOf: 'decision' } }; + expect(kinds((await judge(chain(step('a1'), n('x', 'hold'), step('a2')), { descriptors })).gaps)).toEqual(['pause_between_steps']); + expect((await judge(chain(step('a1'), n('x', 'branch'), step('a2')), { descriptors })).gaps).toEqual([]); + }); + + it('does not refuse the revise window of a returned request', async () => { + expect((await judge(chain(step('a1'), n('rev', 'approval_revise'), step('a2')))).gaps).toEqual([]); + }); + + it('refuses a pause after the only step of a loop body, where the step opens again', async () => { + const root = chain(n('l', 'loop', { collection: '{{items}}', body: chain(step('a1'), n('p', 'wait')) })); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('refuses a pause in one of two child runs side by side, where the other branch\'s step can follow it', async () => { + const flows = { C1: chain(step('c1'), n('p', 'wait')), C2: chain(step('c2')) }; + const root = chain(n('par', 'parallel', { + branches: [ + { name: 'one', ...chain(n('s1', 'subflow', { flowName: 'C1' })) }, + { name: 'two', ...chain(n('s2', 'subflow', { flowName: 'C2' })) }, + ], + })); + const out = await judge(root, { flows }); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'C1', node: 'p', type: 'wait', object: 'invoice' }]); + }); + + it('refuses a pause in a catch region, where a step that failed is followed by another', async () => { + const root = chain(n('t', 'try_catch', { try: chain(step('a1')), catch: chain(n('p', 'wait')) }), step('a2')); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); +}); + +describe('the opening check: D5 condition 5, a map with an approval body', () => { + const body = { B: chain(step('b1')) }; + const map = (collection: unknown, extra: Record = {}) => n('m', 'map', { flowName: 'B', collection, ...extra }); + + it.each([ + ['ahead of', [map('{{record.lines}}'), step('a1')]], + ['between', [step('a1'), map('{{record.lines}}'), step('a2')]], + ['after', [step('a1'), map('{{record.lines}}')]], + ] as const)('refuses a map whose items are read from an expression, %s the parent\'s steps', async (_where, nodes) => { + const out = await judge(chain(...nodes), { flows: body }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('refuses it also where the node names an object for its items', async () => { + const objects = { invoice: invoice(), invoice_line: { name: 'invoice_line', fields: {} } }; + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice_line' })), { flows: body, objects }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('reads items written out with none a record as steps of the parent, and refuses one that is a record', async () => { + const plain = await judge(chain(step('a1'), map([{ amount: 1 }, { amount: 2 }])), { flows: body }); + expect(plain.gaps).toEqual([]); + // As steps of the parent, the body's step is held to condition 4 on the parent's object. + const otherField = await judge(chain(step('a1'), map([{ amount: 1 }])), { flows: { B: chain(step('b1', 'other_status')) } }); + expect(otherField.gaps).toEqual([{ kind: 'other_field', flow: 'B', step: 'b1', object: 'invoice', field: 'status', other: 'other_status' }]); + const oneRecord = await judge(chain(step('a1'), map([{ amount: 1 }, { id: 'inv-2' }])), { flows: body }); + expect(oneRecord.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('does not refuse a map whose parent\'s object the conditions do not concern', async () => { + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice' })), { flows: body, rootObject: 'memo' }); + expect(kinds(out.gaps)).not.toContain('map_with_approval'); + expect(out.gaps).toEqual([]); + }); + + it('does not refuse the batch of a run with no record', async () => { + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows: body, rootObject: null }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + }); + + it('stamps a map body including its only step', async () => { + const flows = { B: chain(n('p', 'assignment'), step('b1'), n('q', 'assignment')) }; + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows, rootObject: 'memo' }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([ + { flow: 'B', node: 'b1' }, { flow: 'B', node: 'end' }, { flow: 'B', node: 'p' }, { flow: 'B', node: 'q' }, { flow: 'B', node: 'start' }, + { flow: 'F', node: 'm' }, + ]); + }); +}); + +describe('the opening check: the stamp', () => { + it('leaves out a branch that passes over the remaining steps', async () => { + const root: OpeningFlowBody = { + nodes: [n('start', 'start'), step('a1'), n('d', 'decision'), step('a2'), n('end', 'end'), n('skip', 'assignment'), n('end2', 'end')], + edges: [ + { source: 'start', target: 'a1' }, { source: 'a1', target: 'd' }, { source: 'd', target: 'a2' }, + { source: 'a2', target: 'end' }, { source: 'd', target: 'skip' }, { source: 'skip', target: 'end2' }, + ], + }; + const out = await judge(root); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd' }]); + }); + + it('follows a subflow into its body', async () => { + const flows = { S: chain(n('x', 'assignment'), step('a2')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'sub' }, { flow: 'S', node: 'start' }, { flow: 'S', node: 'x' }]); + }); + + it('does not count a subflow after the last step as between', async () => { + const flows = { S: chain(n('x', 'assignment')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.between).toEqual([]); + }); +}); + +describe('the opening check: what it does not read, and what it cannot', () => { + it('reads nothing more of an approval whose objects declare no closedStates', async () => { + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2', null)), { rootObject: 'memo', host: false }); + expect(out).toMatchObject({ touchesClosedStates: false, between: [], gaps: [] }); + expect(new Set(out.read)).toEqual(new Set(['memo'])); + }); + + it('refuses an approval one of whose flows cannot be read', async () => { + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'missing' }))); + expect(out.gaps).toContainEqual({ kind: 'unreadable_flow', flow: 'missing' }); + const noRoot = await judgeApprovalOpening({ rootFlow: null, rootFlowName: 'gone', rootObject: 'invoice' }, source({})); + expect(noRoot.gaps).toEqual([{ kind: 'unreadable_flow', flow: 'gone' }]); + }); + + it('refuses on a host that runs no job service, for an approval touching a closing object', async () => { + const out = await judge(chain(step('a1', null)), { host: false }); + expect(out.gaps).toEqual([{ kind: 'no_job_service', object: 'invoice' }]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts new file mode 100644 index 00000000000..d5f3d62e880 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -0,0 +1,28 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7 "The check"] The check when an approval + * opens, read off the approval's definition at its first request. + * + * The judge itself lives in `@objectstack/metadata-core` + * (`approval-opening.ts`), because the authoring rule + * `validateApprovalClosedStates` (`@objectstack/lint`) asks the same + * conditions at every authoring door, and one copy of the judge is what keeps + * the two from disagreeing (maintainer ruling 7253749311 on #37766). The + * first request reads the engine asynchronously, so it calls + * {@link judgeApprovalOpening}; this module keeps the plugin's import path. + */ + +export { + closedValuesOf, + judgeApprovalOpening, + type BetweenNode, + type OpeningCheckInput, + type OpeningCheckSource, + type OpeningFlow, + type OpeningFlowBody, + type OpeningFlowEdge, + type OpeningFlowNode, + type OpeningGap, + type OpeningJudgement, +} from '@objectstack/metadata-core'; diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts new file mode 100644 index 00000000000..5ea0e31c29b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.test.ts @@ -0,0 +1,72 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7] The lead of the refusal at an approval's first + * request says the object closes on its approval field only where a gap is + * about that field. The host's gap (`no_job_service`) and a flow that could + * not be read (`unreadable_flow`) are raised on an object that declares + * `closedStates` on any field, so where they are the only gaps the lead says + * what is true in every case: the approval can act on an object that declares + * `closedStates`. + * + * The expected sentences are read from the catalog, not written out here: what + * these tests hold is WHICH lead is chosen, and in which pack; the wording is + * the catalog's, and `approval-notification-keyed-text.integration.test.ts` holds every locale + * to the same ids and holes. + */ + +import { describe, expect, it } from 'vitest'; +import { interpolate } from './approval-notification-text.js'; +import type { OpeningGap } from './approval-opening-check.js'; +import { openingRefusalText } from './approval-opening-refusal.js'; +import { approvalMessages } from './translations/messages.js'; + +const subject = { object: 'crm_deal', record: 'd1' }; +type Locale = keyof typeof approvalMessages; +const fieldLead = (locale: Locale) => interpolate(approvalMessages[locale].approvalOpeningRefusedLead, subject); +const neutralLead = (locale: Locale) => interpolate(approvalMessages[locale].approvalOpeningRefusedClosedStatesLead, subject); +const sentence = (gap: OpeningGap, id: 'approvalOpeningNoJobService' | 'approvalOpeningUnreadableFlow') => { + const { kind: _kind, ...params } = gap; + return interpolate(approvalMessages.en[id], params as Record); +}; + +const host: OpeningGap = { kind: 'no_job_service', object: 'crm_deal' }; +const unreadable: OpeningGap = { kind: 'unreadable_flow', flow: 'deal_sub' }; +const pause: OpeningGap = { kind: 'pause_between_steps', flow: 'deal_flow', node: 'hold', type: 'wait', object: 'crm_deal' }; + +describe('the opening refusal: its lead', () => { + it('the two leads are two sentences, in every pack', () => { + for (const locale of Object.keys(approvalMessages) as Locale[]) { + expect(neutralLead(locale), locale).not.toBe(fieldLead(locale)); + } + }); + + it('does not say the object closes on its approval field where the host\'s gap is the only one', () => { + const text = openingRefusalText([host], subject, 'en'); + expect(text).toBe(`${neutralLead('en')} ${sentence(host, 'approvalOpeningNoJobService')}`); + }); + + it('does not say it where a flow that could not be read is the only gap', () => { + const text = openingRefusalText([unreadable], subject, 'en'); + expect(text).toBe(`${neutralLead('en')} ${sentence(unreadable, 'approvalOpeningUnreadableFlow')}`); + }); + + it('does not say it where the host\'s gap and an unreadable flow are the only gaps', () => { + const text = openingRefusalText([unreadable, host], subject, 'en'); + expect(text.startsWith(`${neutralLead('en')} `)).toBe(true); + expect(text).not.toContain(fieldLead('en')); + }); + + it('says it where a gap is about the field, alone or beside the host\'s', () => { + expect(openingRefusalText([pause], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + expect(openingRefusalText([pause, host], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + expect(openingRefusalText([host, pause], subject, 'en').startsWith(`${fieldLead('en')} `)).toBe(true); + }); + + it('words the lead that says nothing about the field in the run\'s locale', () => { + const text = openingRefusalText([host], subject, 'zh-CN'); + expect(text.startsWith(`${neutralLead('zh-CN')} `)).toBe(true); + expect(text).not.toContain(fieldLead('zh-CN')); + expect(neutralLead('zh-CN')).not.toBe(neutralLead('en')); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts new file mode 100644 index 00000000000..6251c07bab4 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -0,0 +1,80 @@ +/** + * The sentence an approval's first request is refused with when the opening + * check (ADR-0162 Execution item 7, #37766 slice B) finds a gap: one lead + * naming the record, then one sentence per gap naming the flow, step, object, + * field and what is missing — in the run's locale, from the plugin's own + * catalog (`translations/messages.ts`), falling back to `en`. + */ + +import { interpolate } from './approval-notification-text.js'; +import type { OpeningGap } from './approval-opening-check.js'; +import { approvalMessages, type ApprovalMessageId } from './translations/messages.js'; + +type Pack = (typeof approvalMessages)[keyof typeof approvalMessages]; + +const GAP_SENTENCE: Readonly> = { + no_pending_option: 'approvalOpeningNoPendingOption', + closes_in_flight: 'approvalOpeningClosesInFlight', + state_machine_no_pending: 'approvalOpeningStateMachine', + readonly_when: 'approvalOpeningReadonlyWhen', + option_visible_when: 'approvalOpeningOptionVisibleWhen', + other_field: 'approvalOpeningOtherField', + no_field: 'approvalOpeningNoField', + pause_between_steps: 'approvalOpeningPause', + map_with_approval: 'approvalOpeningMapApproval', + unreadable_flow: 'approvalOpeningUnreadableFlow', + no_job_service: 'approvalOpeningNoJobService', +}; + +/** + * The catalog pack for `locale`: the exact tag; else `zh-Hant` for a + * Traditional Chinese tag (`zh-TW`, `zh-HK`, `zh-MO`); else the first pack of + * the same language; else `en`. + */ +export function openingRefusalPack(locale: string | undefined): Pack { + const packs = approvalMessages as Readonly>; + if (!locale) return approvalMessages.en; + const wanted = locale.replace(/_/g, '-').toLowerCase(); + const tags = Object.keys(packs); + const exact = tags.find((t) => t.toLowerCase() === wanted); + if (exact) return packs[exact]!; + if (/^zh-(hant|tw|hk|mo)\b/.test(wanted) && packs['zh-Hant']) return packs['zh-Hant']!; + const language = wanted.split('-')[0]; + const same = tags.find((t) => t.toLowerCase().split('-')[0] === language); + return same ? packs[same]! : approvalMessages.en; +} + +/** + * The gaps that say nothing about the approval field: the host's, and a flow + * that could not be read. Where every gap is one of these, the lead does not + * say the object closes on its approval field, which may be false: an object + * can declare `closedStates` on another field. + */ +const NOT_ABOUT_THE_FIELD: ReadonlySet = new Set(['no_job_service', 'unreadable_flow']); + +/** + * Whether any of `gaps` is about the approval field, so that "the object + * closes on its approval field" is true of the refusal. The one rule for every + * text that says so: the refusal's lead here, and the service's log line. + */ +export function gapsAreAboutTheField(gaps: readonly OpeningGap[]): boolean { + return gaps.some((gap) => !NOT_ABOUT_THE_FIELD.has(gap.kind)); +} + +/** The refusal text for `gaps`, on the record `subject`, in `locale`. */ +export function openingRefusalText( + gaps: readonly OpeningGap[], + subject: { object: string; record: string }, + locale?: string, +): string { + const pack = openingRefusalPack(locale); + const lead = interpolate( + gapsAreAboutTheField(gaps) ? pack.approvalOpeningRefusedLead : pack.approvalOpeningRefusedClosedStatesLead, + { object: subject.object, record: subject.record }, + ); + const sentences = gaps.map((gap) => { + const { kind, ...params } = gap; + return interpolate(pack[GAP_SENTENCE[kind]], params as Record); + }); + return [lead, ...sentences].join(' '); +} diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts new file mode 100644 index 00000000000..08297d72bc1 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -0,0 +1,579 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The outcome when the approval is over", + * #37767 slice 3] On a field the object closes on at `approved` or + * `rejected`, every step's decision is held back and the field keeps + * `pending` until the approval is over for the record. After each door that + * resumes or cancels a run of the approval, the plugin reads the run that + * carries the record and asks its own table for a request of the approval on + * the record: finished, it writes the decision of the approval's latest + * request; in progress, nothing; ended between two steps, it abandons the + * approval and puts the field back; cannot tell, nothing, and the mark stays. + * + * Each case records the value the field keeps. Real kernel, real ObjectQL + * engine, real automation engine, real approval node, driver-sql on + * better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + // Two steps: the second opens in the segment the first decision resumes. + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // Two steps and a node after the last that reads the record. + flow('two_step_then_read', [step('first', 'approver'), step('second', 'approver2'), mark('read')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'read', 'approve'), edge('second', 'read', 'reject'), edge('read', 'end')]), + // A timer after the last step. + flow('wait_after', [step('first', 'approver'), step('second', 'approver2'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'hold', 'approve'), edge('second', 'end', 'reject'), edge('hold', 'end')]), + // A node that fails after the last step. + flow('fail_after', [step('first', 'approver'), step('second', 'approver2'), mark('boom')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'boom', 'approve'), edge('second', 'end', 'reject'), edge('boom', 'end')]), + // The second step resolves to no one under `fail`: unrouted, with a fault edge to the end, and with one to a third step. + flow('second_empty', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + flow('second_empty_fault_end', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'end', undefined, 'fault')]), + flow('second_empty_fault_third', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' }), step('third', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'third', undefined, 'fault'), ...decided('third', 'end')]), + // Another node between two steps fails: with a fault edge to the end, and unrouted. + flow('boom_between_fault_end', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + // The same two steps in a `subflow` child, whose steps the parent's run does not log. + flow('parent_of_boom', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'boom_between_fault_end' } }], + [edge('start', 'sub'), edge('sub', 'end')]), + // That node's failure handled in a try_catch region, after which a gateway ends the flow. + flow('boom_handled', [step('first', 'approver'), + { id: 'guard', type: 'try_catch', label: 'Guard', config: { try: { nodes: [mark('boom')], edges: [] }, catch: { nodes: [mark('handled')], edges: [] } } }, + { id: 'gate', type: 'decision', label: 'Gate' }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'guard', 'approve'), edge('first', 'end', 'reject'), edge('guard', 'gate'), + { id: 'gate_end', source: 'gate', target: 'end', condition: 'true' }, + { id: 'gate_second', source: 'gate', target: 'second', condition: 'false' }, + ...decided('second', 'end')]), + // The second step can send back into a revise window. + flow('second_revise', [step('first', 'approver'), step('second', 'approver2'), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The same, with no send-back left: a send-back auto-rejects. + flow('second_revise_spent', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The first step's reject edge to an `end` that refuses: the run ends `refused`, an `end` logging no step. + flow('refuse_on_reject', [step('first', 'approver'), step('second', 'approver2'), + { id: 'refuse', type: 'end', label: 'Refuse', config: { outcome: 'refused', message: 'Refused' } }], + [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'refuse', 'reject'), ...decided('second', 'end')]), + // A node before the first step fails and is routed on; the first step is in a `subflow` child, the second after it. + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + flow('early_fault_then_sub', [mark('early'), { id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'early'), edge('early', 'sub'), edge('early', 'sub', undefined, 'fault'), edge('sub', 'second'), ...decided('second', 'end')]), + // A batch whose items are records, each approved in its own run of `item_step`. + flow('item_step', [step('only', 'approver'), mark('after')], [edge('start', 'only'), edge('only', 'after', 'approve'), edge('only', 'end', 'reject'), edge('after', 'end')]), + { name: 'batch', label: 'batch', type: 'autolaunched', variables: [{ name: 'items', type: 'list', isInput: true }], + nodes: [START, { id: 'each', type: 'map', label: 'Each', config: { collection: { dialect: 'cel', source: 'items' }, flowName: 'item_step', itemObject: 'crm_invoice' } }, END], + edges: [edge('start', 'each'), edge('each', 'end')] }, +]; + +describe('[ADR-0162 item 8] the outcome is written when the approval is over', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + seen = []; + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, order, claim, ticket, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => [r.flow_node_id, r.status]); + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + describe('the decision is held back, and written when the approval is over', () => { + it('two steps approved: the field reads pending after the first and approved once the run ends; marks are set and cleared', async () => { + // Every value written to the field, in order: the second step's opening + // writes `pending` straight after the first decision, so the field read + // alone cannot tell a held-back decision from a written one. + const written: unknown[] = []; + const update = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, opts?: any) => { + if (object === 'crm_invoice' && data?.id === 'i_two' && 'approval_status' in data) written.push(data.approval_status); + return update(object, data, opts); + }; + expect((await start('two_step', 'crm_invoice', 'i_two')).status).toBe('paused'); + await decide('i_two', 'approve', 'approver'); + expect(await steps('i_two')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await field('crm_invoice', 'i_two'), 'the first decision is held back').toBe('pending'); + expect(await marks('i_two'), 'the next request opened, so the first decision\'s passage ended').toEqual([false, false]); + + await decide('i_two', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_two')).toBe('approved'); + expect(written, 'the first decision was never written onto the record').toEqual(['pending', 'pending', 'approved']); + expect(await marks('i_two'), 'judged: no mark stands').toEqual([false, false]); + }); + + it('a node after the last decision reads pending; the outcome lands as the run ends', async () => { + await start('two_step_then_read', 'crm_invoice', 'i_read'); + await decide('i_read', 'approve', 'approver'); + await decide('i_read', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_invoice', 'i_read')).toBe('approved'); + }); + + it('a second step that rejects on an object that closes on approved alone: pending until the approval is over, then rejected', async () => { + await start('two_step_then_read', 'crm_order', 'o_rej'); + await decide('o_rej', 'approve', 'approver'); + expect(await field('crm_order', 'o_rej'), 'the first decision is held back').toBe('pending'); + await decide('o_rej', 'reject', 'approver2'); + expect(seen, 'held back although the object does not close on rejected').toEqual(['pending']); + expect(await field('crm_order', 'o_rej')).toBe('rejected'); + }); + + it('a first step that approves on an object that closes on rejected alone: pending until the approval is over', async () => { + await start('two_step_then_read', 'crm_claim', 'c_app'); + await decide('c_app', 'approve', 'approver'); + expect(await field('crm_claim', 'c_app'), 'the object does not close on approved, and it is held back all the same').toBe('pending'); + await decide('c_app', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_claim', 'c_app')).toBe('approved'); + }); + + it('a wait after the last step: the outcome is written as the run parks', async () => { + await start('wait_after', 'crm_invoice', 'i_wait'); + await decide('i_wait', 'approve', 'approver'); + await decide('i_wait', 'approve', 'approver2'); + expect((await automation.getRun(String((await requestsOn('i_wait'))[0].record_run_id)))?.status).toBe('paused'); + expect(await field('crm_invoice', 'i_wait')).toBe('approved'); + }); + + it('a node that fails after the last step: the outcome stands', async () => { + await start('fail_after', 'crm_invoice', 'i_fail_after'); + await decide('i_fail_after', 'approve', 'approver'); + throwOn.add('boom'); + const out = await settle(decide('i_fail_after', 'approve', 'approver2')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + expect(await field('crm_invoice', 'i_fail_after')).toBe('approved'); + expect(await marks('i_fail_after')).toEqual([false, false]); + }); + + it('the outcome is written in the name of the person who decided the last step', async () => { + await start('two_step', 'crm_invoice', 'i_who'); + await decide('i_who', 'approve', 'approver'); + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, options?: any) => { + if (object === 'crm_invoice') writes.push([data.approval_status, options?.context?.userId, options?.context?.isSystem]); + return original(object, data, options); + }; + await decide('i_who', 'approve', 'approver2'); + expect(writes).toEqual([['approved', 'approver2', true]]); + }); + }); + + describe('a map item that is a record', () => { + it('its outcome does not wait for the later items, and a later item\'s failure does not undo it', async () => { + await seed('crm_invoice', 'i_m1'); + await seed('crm_invoice', 'i_m2'); + const items = [await read('crm_invoice', 'i_m1'), await read('crm_invoice', 'i_m2')]; + const batch: any = await automation.execute('batch', { params: { items }, userId: 'owner' } as any); + expect(batch.status).toBe('paused'); + + await decide('i_m1', 'approve', 'approver'); + expect(await pendingOn('i_m2'), 'the next item is in approval').toBeTruthy(); + expect(await field('crm_invoice', 'i_m1'), 'the first item\'s approval is over for its record').toBe('approved'); + + throwOn.add('after'); + await settle(decide('i_m2', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_m1')).toBe('approved'); + // A node after the last step of a `map` body stands before that step's + // next opening (ADR-0162 D5): the second item's run stopped between two + // steps, and only its own record is put back. + expect(await field('crm_invoice', 'i_m2')).toBe('recalled'); + }); + }); + + describe('an abandoned latest request: nothing is written', () => { + it('a first step approved, a second recalled, and a run that then completes: no approved', async () => { + await start('two_step', 'crm_invoice', 'i_recall'); + await decide('i_recall', 'approve', 'approver'); + const second = await pendingOn('i_recall'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + const run = await automation.getRun(String(second.record_run_id)); + expect(run?.status).toBe('completed'); + expect(await steps('i_recall')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_recall')).toBe('recalled'); + expect(await marks('i_recall')).toEqual([false, false]); + }); + + it('the same for a returned request recalled in its revise window', async () => { + await start('second_revise', 'crm_invoice', 'i_revise'); + await decide('i_revise', 'approve', 'approver'); + const second = await pendingOn('i_revise'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_revise')).toBe('returned'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await steps('i_revise')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_revise')).toBe('recalled'); + expect(await marks('i_revise')).toEqual([false, false]); + }); + }); + + describe('the other doors', () => { + it('a send-back, a resubmission and the decision of the new round: the field reads returned, then pending, then approved', async () => { + await start('second_revise', 'crm_invoice', 'i_round'); + await decide('i_round', 'approve', 'approver'); + const second = await pendingOn('i_round'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_round')).toBe('returned'); + await svc.resubmit(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await field('crm_invoice', 'i_round')).toBe('pending'); + await decide('i_round', 'approve', 'approver2'); + expect(await steps('i_round')).toEqual([['first', 'approved'], ['second', 'returned'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_round')).toBe('approved'); + expect(await marks('i_round')).toEqual([false, false, false]); + }); + + it('a send-back past the revision limit auto-rejects: held back, then written when the approval is over', async () => { + await start('second_revise_spent', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + const second = await pendingOn('i_spent'); + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await steps('i_spent')).toEqual([['first', 'approved'], ['second', 'rejected']]); + expect(await field('crm_invoice', 'i_spent')).toBe('rejected'); + expect(await marks('i_spent')).toEqual([false, false]); + }); + + it('a recall clears a mark an earlier decision of the approval left', async () => { + await start('two_step', 'crm_invoice', 'i_clear'); + await decide('i_clear', 'approve', 'approver'); + const [first, second] = await requestsOn('i_clear'); + // The shape a process that died before the next request cleared it leaves. + await ql.update('sys_approval_request', { id: first.id, unjudged_since: new Date().toISOString() }, { context: SYS }); + expect(await marks('i_clear')).toEqual([true, false]); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await marks('i_clear')).toEqual([false, false]); + expect(await field('crm_invoice', 'i_clear')).toBe('recalled'); + }); + }); + + describe('a later step that cannot open', () => { + it('on an empty slate, unrouted: the approval is abandoned and the field is put back', async () => { + await start('second_empty', 'crm_invoice', 'i_empty'); + const out = await settle(decide('i_empty', 'approve', 'approver')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const [first] = await requestsOn('i_empty'); + expect(first.status, 'the decision stays on its request').toBe('approved'); + expect(await field('crm_invoice', 'i_empty')).toBe('recalled'); + expect(JSON.parse(first.node_config_json).__abandoned).toBeTruthy(); + expect(JSON.parse(first.node_config_json).__laterStepNotOpened.node).toBe('second'); + const line = (await timeline(String(first.id))).at(-1)!; + expect(line.slice(0, 2), 'a line with no actor').toEqual(['comment', null]); + expect(line[2]).toMatch(/^The approval did not go on: its step 'second' could not open \(.*NO_APPROVERS.*\)\. The record's approval_status was put back to 'recalled'\.$/); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.approved'), 'no approved notice for an approval that did not finish').toBe(false); + expect(await marks('i_empty')).toEqual([false]); + }); + + it('with a fault edge to the end: abandoned', async () => { + await start('second_empty_fault_end', 'crm_invoice', 'i_empty_end'); + await decide('i_empty_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_empty_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_empty_end')).toBe('recalled'); + }); + + it('with a fault edge to another step, which opens: in progress, then finished', async () => { + await start('second_empty_fault_third', 'crm_invoice', 'i_empty_third'); + await decide('i_empty_third', 'approve', 'approver'); + expect(await steps('i_empty_third')).toEqual([['first', 'approved'], ['third', 'pending']]); + expect(await field('crm_invoice', 'i_empty_third')).toBe('pending'); + await decide('i_empty_third', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_empty_third')).toBe('approved'); + }); + + it('on a request of another approval already pending on the record: the field keeps that approval\'s pending', async () => { + await start('two_step', 'crm_invoice', 'i_dup'); + const [first] = await requestsOn('i_dup'); + // Another approval's request on the record, on the same field: the + // shape a second approval leaves when it opens between two steps. + await ql.insert('sys_approval_request', { + id: 'areq_other', process_name: 'flow:other', object_name: 'crm_invoice', record_id: 'i_dup', status: 'pending', + root_run_id: 'run_other', record_run_id: 'run_other', flow_run_id: 'run_other', flow_node_id: 'x', + node_config_json: JSON.stringify({ approvers: [], approvalStatusField: 'approval_status' }), + organization_id: ORG, created_at: new Date().toISOString(), + }, { context: SYS }); + const out = await settle(svc.decide(String(first.id), { decision: 'approve', actorId: 'approver' } as any, asPerson('approver'))); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const mine = (await requestsOn('i_dup')).filter((r) => r.root_run_id !== 'run_other'); + expect(mine.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved']]); + expect(JSON.parse(mine[0].node_config_json).__abandoned).toBeTruthy(); + expect(await field('crm_invoice', 'i_dup')).toBe('pending'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/left as it is: the request 'areq_other' of another approval is open on it\.$/); + }); + }); + + describe('another node between two steps fails', () => { + it('with a fault edge to the end: abandoned', async () => { + await start('boom_between_fault_end', 'crm_invoice', 'i_boom_end'); + throwOn.add('boom'); + await decide('i_boom_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_boom_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_boom_end')).toBe('recalled'); + const [first] = await requestsOn('i_boom_end'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + }); + + it('in a subflow child, with a fault edge to the child\'s end: abandoned, read off the child\'s own run', async () => { + await start('parent_of_boom', 'crm_invoice', 'i_child'); + throwOn.add('boom'); + await decide('i_child', 'approve', 'approver'); + const [first] = await requestsOn('i_child'); + expect(first.flow_run_id, 'the request is the child run\'s').not.toBe(first.record_run_id); + expect((await automation.getRun(String(first.record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_child')).toBe('recalled'); + }); + + it('handled in a try_catch region, after which a gateway ends the flow: finished', async () => { + await start('boom_handled', 'crm_invoice', 'i_handled'); + throwOn.add('boom'); + await decide('i_handled', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_handled'))[0].record_run_id)))?.status).toBe('completed'); + expect(await steps('i_handled')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_handled')).toBe('approved'); + }); + + it('unrouted: the run fails between two steps, the approval is abandoned, and a restored run is refused', async () => { + await start('boom_between', 'crm_invoice', 'i_boom'); + throwOn.add('boom'); + const out = await settle(decide('i_boom', 'approve', 'approver')); + expect('error' in out && strandedDecisionDetails(out.error)?.repairable).toBe(true); + expect(await field('crm_invoice', 'i_boom')).toBe('recalled'); + const [first] = await requestsOn('i_boom'); + + throwOn.clear(); + const restored = await (automation as any).restoreConsumedSuspension(String(first.flow_run_id), { requestedBy: 'ops', reason: 'test' }); + expect(restored.restored).toBe(true); + const refused = await settle(svc.continueRestoredRun(String(first.id))); + expect('error' in refused && refused.error.message).toMatch(/^INVALID_STATE: .*was abandoned when its run ended between two steps.*Cancel the restored run/); + expect(await steps('i_boom'), 'no next step opened').toEqual([['first', 'approved']]); + }); + }); + + describe('an approval that holds nothing back, and the control', () => { + it('an object whose closed states are on another field: the decision is written at once, the mark is set and cleared', async () => { + await start('two_step_then_read', 'crm_ticket', 't_two'); + const [first] = await requestsOn('t_two'); + expect(first.between_steps_json, 'stamped: the object declares the key').toBeTruthy(); + await decide('t_two', 'approve', 'approver'); + await decide('t_two', 'approve', 'approver2'); + expect(seen, 'as on main: a node after the decision reads it').toEqual(['approved']); + expect(await field('crm_ticket', 't_two')).toBe('approved'); + expect(await marks('t_two')).toEqual([false, false]); + }); + + it('the same object, whose run ends between two steps: nothing is written and the mark is cleared', async () => { + await start('boom_between_fault_end', 'crm_ticket', 't_boom'); + throwOn.add('boom'); + await decide('t_boom', 'approve', 'approver'); + const [first] = await requestsOn('t_boom'); + expect(await field('crm_ticket', 't_boom')).toBe('approved'); + expect(JSON.parse(first.node_config_json).__abandoned ?? null).toBeNull(); + expect(await marks('t_boom')).toEqual([false]); + }); + + it('an object that declares no closed state: unstamped, no mark, written as before', async () => { + await start('two_step_then_read', 'crm_memo', 'm_two'); + await decide('m_two', 'approve', 'approver'); + await decide('m_two', 'approve', 'approver2'); + const rows = await requestsOn('m_two'); + expect(rows.map((r) => r.between_steps_json ?? null)).toEqual([null, null]); + expect(rows.map((r) => r.unjudged_since ?? null)).toEqual([null, null]); + expect(seen).toEqual(['approved']); + expect(await field('crm_memo', 'm_two')).toBe('approved'); + }); + }); + + describe('where a run stopped', () => { + it('a run that ends on a refusing end is finished: the rejection is written, not abandoned', async () => { + await start('refuse_on_reject', 'crm_invoice', 'i_refused'); + await decide('i_refused', 'reject', 'approver'); + const [only] = await requestsOn('i_refused'); + expect((await automation.getRun(String(only.record_run_id)))?.status).toBe('refused'); + expect(await field('crm_invoice', 'i_refused')).toBe('rejected'); + expect(await marks('i_refused')).toEqual([false]); + expect(notices.some((n) => n.topic === 'approval.abandoned')).toBe(false); + expect(notices.filter((n) => n.topic === 'approval.rejected').map((n) => n.audience)).toEqual([['owner']]); + }); + + it('a cancelled run stopped where it stood, not at an earlier failure the flow routed on: abandoned', async () => { + throwOn.add('early'); + await start('early_fault_then_sub', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + expect(child.flow_run_id, 'the request is the child run\'s').not.toBe(child.record_run_id); + await automation.cancelRun(String(child.record_run_id)); + await settle(decide('i_cancel', 'approve', 'approver')); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('cancelled'); + expect(await steps('i_cancel'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel'), 'stopped at the subflow, between two steps').toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + }); + }); + + describe('cannot tell', () => { + it('a run another process is advancing: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_busy'); + await decide('i_busy', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => ({ ...(await original(id)), status: 'running' }); + await decide('i_busy', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_busy')).toBe('pending'); + expect(await marks('i_busy')).toEqual([false, true]); + // The reason names the advancing run, not only an unplaced status: the + // two answer alike, and only the reason tells them apart. + expect(infos.some((m) => m.includes('i_busy') && m.includes("is running, so another process may be advancing it"))).toBe(true); + }); + + it('a run that cannot be read: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_unread'); + await decide('i_unread', 'approve', 'approver'); + (automation as any).getRun = async () => { throw new Error('store down'); }; + await decide('i_unread', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_unread')).toBe('pending'); + expect(await marks('i_unread')).toEqual([false, true]); + expect(infos.some((m) => m.includes('i_unread') && m.includes('could not be read (store down)'))).toBe(true); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts new file mode 100644 index 00000000000..7f4424c4dad --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -0,0 +1,1748 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The reconciler", #37767 piece 4] The door + * reads every run of an approval's tree, and the reconciler judges every + * approval whose mark no door cleared. + * + * The door follows the child runs each delegating step records + * (`childRunIds`): a sibling `subflow` child, a middle run two levels down, + * a run another process is advancing. The reconciler scans the mark oldest + * first and judges each approval as the door would have: a parent run that + * was cancelled while its child's request was pending, a process that died + * between a decision and the write of its outcome, an approval whose field + * the object does not close on, a record deleted in a passage, and, past + * the age bound, a run whose pause is gone and a run parked at a `subflow` + * whose child has ended. + * + * Real kernel, real ObjectQL engine, real automation engine, real approval + * node, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, MAX_PERSISTED_HISTORY_STEPS, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService, HISTORY_STEPS_KEPT, MAX_RUNS_READ_PER_APPROVAL, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +/** A start node whose condition never holds: the flow is skipped and starts no run. */ +const GATED_START = { id: 'start', type: 'start', label: 'Start', config: { condition: '1 == 2' } }; +const WAIT = { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }; + +const FLOWS = [ + // [M1] A child flow its start condition skips: the call starts no run. + { name: 'child_gated', label: 'child_gated', type: 'autolaunched', nodes: [GATED_START, mark('noop'), END], edges: [edge('start', 'noop'), edge('noop', 'end')] }, + flow('gated_sub_between', [step('first', 'approver'), { id: 'gate', type: 'subflow', label: 'Gate', config: { flowName: 'child_gated' } }, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'gate', 'approve'), edge('first', 'end', 'reject'), edge('gate', 'second'), ...decided('second', 'end')]), + // [ruling A3] A child that ends before the first step opens. + flow('child_noop', [mark('noop')], [edge('start', 'noop'), edge('noop', 'end')]), + flow('early_sub_two_step', [{ id: 'prep', type: 'subflow', label: 'Prepare', config: { flowName: 'child_noop' } }, step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'prep'), edge('prep', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // [M3] A node between the two steps that fails, routed to a pause no step follows. + flow('routed_to_wait', [step('first', 'approver'), mark('boom'), WAIT, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), + edge('boom', 'hold', undefined, 'fault'), edge('hold', 'end'), ...decided('second', 'end')]), + // [S3] A map item run that holds no request: its node fails before the item's step, routed to its end. + flow('first_then_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1] } }], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + // A sibling child after the child that holds the first step: a node that + // fails before its step, routed to the child's end. + flow('child_boom_then_step', [mark('boom'), step('second', 'approver2')], + [edge('start', 'boom'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('parent_two_subs', [ + { id: 'sub1', type: 'subflow', label: 'First', config: { flowName: 'child_one_step' } }, + { id: 'sub2', type: 'subflow', label: 'Second', config: { flowName: 'child_boom_then_step' } }], + [edge('start', 'sub1'), edge('sub1', 'sub2'), edge('sub2', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the + // first step and holds the second after a node that fails, unrouted. + flow('middle_boom', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }, mark('boom'), step('second', 'approver2')], + [edge('start', 'inner'), edge('inner', 'boom'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('root_of_middle', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'middle_boom' } }], + [edge('start', 'mid'), edge('mid', 'end'), edge('mid', 'end', undefined, 'fault')]), + // A child step, then a step in the parent. + flow('sub_then_second', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'sub'), edge('sub', 'second'), ...decided('second', 'end')]), + // A node between the two steps that fails, unrouted: the run fails there. + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // A send-back past the limit auto-rejects the second step, whose reject + // edge runs a node that fails before the third step, routed to the end. + flow('spent_then_boom', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), + { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }, mark('boom'), step('third', 'approver')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'third', 'approve'), edge('second', 'boom', 'reject'), + edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }, + edge('boom', 'third'), edge('boom', 'end', undefined, 'fault'), ...decided('third', 'end')]), + // ── The fixtures of the rebuild on contract review 7257527251 ── + // A child that fails, unrouted. + flow('child_fail', [mark('boom')], [edge('start', 'boom'), edge('boom', 'end')]), + // The only step, then a child that fails: the run fails at `sub`, after its last step. + flow('fail_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('after', 'end')]), + // The same, with the child's failure routed on: the run goes on along the fault edge and completes. + flow('fault_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('sub', 'after', undefined, 'fault'), edge('after', 'end')]), + // A child between the two steps, which ends inside the passage. + flow('sub_between', [step('first', 'approver'), { id: 'mid', type: 'subflow', label: 'Mid', config: { flowName: 'child_noop' } }, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'mid', 'approve'), edge('first', 'end', 'reject'), edge('mid', 'second'), ...decided('second', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the first step; the second step is the root's. + flow('mid_one_step', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }], [edge('start', 'inner'), edge('inner', 'end')]), + flow('root_mid_then_second', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'mid_one_step' } }, step('second', 'approver2')], + [edge('start', 'mid'), edge('mid', 'second'), ...decided('second', 'end')]), + // A root above the two sibling children: the middle run ends over a child the plugin may not have read. + flow('root_of_two_subs', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'parent_two_subs' } }], [edge('start', 'mid'), edge('mid', 'end')]), + // A map whose two items are not records: each item's step is a step of the parent's record. + flow('first_then_two_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1, 2] } }], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), + // ── The fixtures of the rework on contract review 7266979193 ── + // A map whose items are records, between two steps: each item's step is an approval of the item's own record. + flow('first_then_records', [step('first', 'approver'), + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_one_step', collection: [{ id: 'm_line_1' }, { id: 'm_line_2' }], itemObject: 'crm_memo' } }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'second'), ...decided('second', 'end')]), + // The only step, then a map of one item more than the engine names on a step; the items are not records. + flow('only_then_fan', [step('only', 'approver'), + { id: 'fan', type: 'map', label: 'Fan', config: { flowName: 'child_noop', collection: Array.from({ length: 201 }, (_, i) => i) } }], + [edge('start', 'only'), edge('only', 'fan', 'approve'), edge('only', 'end', 'reject'), edge('fan', 'end')]), + // A child between the two steps, one of whose nodes carries the id of the parent's last step. + flow('child_named_final', [mark('final')], [edge('start', 'final'), edge('final', 'end')]), + flow('gate_sub_final', [step('gate', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_named_final' } }, step('final', 'approver2')], + [edge('start', 'gate'), edge('gate', 'sub', 'approve'), edge('gate', 'end', 'reject'), edge('sub', 'final'), ...decided('final', 'end')]), + // ── The fixture of the patch on delta review 7269135624 ── + // A wait between the two steps that outlasts the age bound by design, then a node before the second step. + flow('wait_between', [step('first', 'approver'), WAIT, mark('probe'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'hold', 'approve'), edge('first', 'end', 'reject'), edge('hold', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), +]; + +describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What runs while a node of type `mark` executes, by id: inside the passage that reached it. */ + let during: Map Promise>; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + during = new Map(); + seen = []; + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, order, claim, ticket, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + await during.get(node.id)?.(); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => [r.flow_node_id, r.status]); + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + + /** Run `fn` with no door judging: the shape a process that died after the door's own action leaves. */ + const withoutDoor = async (fn: () => Promise): Promise => { + const judge = (svc as any).judgeApprovalAfterDoor; + (svc as any).judgeApprovalAfterDoor = async () => 'undetermined'; + try { return await fn(); } finally { (svc as any).judgeApprovalAfterDoor = judge; } + }; + /** Move every mark on the record's requests past the reconciler's age bound. */ + const age = async (id: string) => { + const past = new Date(Date.now() - 2 * RECONCILER_AGE_BOUND_MS).toISOString(); + for (const r of await requestsOn(id)) { + if (r.unjudged_since != null) await ql.update('sys_approval_request', { id: r.id, unjudged_since: past }, { context: SYS }); + } + }; + const recordWrites = (object: string) => { + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === object && 'approval_status' in (data ?? {})) writes.push([data.approval_status, options?.context?.userId ?? null]); + return original(o, data, options); + }; + return writes; + }; + + describe('the door reads every run of the approval', () => { + it('a sibling subflow child whose node failed before its step, routed to its end: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_sib'); + throwOn.add('boom'); + await decide('i_sib', 'approve', 'approver'); + const [first] = await requestsOn('i_sib'); + expect((await automation.getRun(String(first.record_run_id)))?.status, 'the carrying run completed').toBe('completed'); + expect(await steps('i_sib'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_sib')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_sib')).toEqual([false]); + }); + + it('the delegating steps record the child runs they started', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_links'); + await decide('i_links', 'approve', 'approver'); + const [first] = await requestsOn('i_links'); + const root: any = await automation.getRun(String(first.record_run_id)); + const sub1 = root.steps.filter((s: any) => s.nodeId === 'sub1'); + expect(sub1.length).toBeGreaterThan(0); + for (const s of sub1) expect(s.childRunIds).toEqual([String(first.flow_run_id)]); + const sub2 = root.steps.find((s: any) => s.nodeId === 'sub2'); + expect(sub2.childRunIds).toHaveLength(1); + expect(sub2.childRunIds[0]).not.toBe(String(first.flow_run_id)); + expect(root.steps.find((s: any) => s.nodeId === 'start').childRunIds).toBeUndefined(); + }); + + it('a middle run, two levels down, that failed between two steps: abandoned', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid'); + throwOn.add('boom'); + await settle(decide('i_mid', 'approve', 'approver')); + const [first] = await requestsOn('i_mid'); + expect(await steps('i_mid')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_mid')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/ended failed at node 'boom', between two steps/); + }); + + it('a middle run another process is advancing: nothing is written, and the mark stays', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid_busy'); + const [first] = await requestsOn('i_mid_busy'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(first.flow_run_id)); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => { + const run: any = await original(id); + return id === middle ? { ...run, status: 'running' } : run; + }; + throwOn.add('boom'); + await settle(decide('i_mid_busy', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_mid_busy')).toBe('pending'); + expect(await marks('i_mid_busy')).toEqual([true]); + expect(infos.some((m) => m.includes(`the run '${middle}' is running, so another process may be advancing it`))).toBe(true); + }); + + it('an abandoned auto-rejection sends the abandoned notice and no auto-rejected one', async () => { + await start('spent_then_boom', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + throwOn.add('boom'); + const second = await pendingOn('i_spent'); + notices.length = 0; + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await field('crm_invoice', 'i_spent')).toBe('recalled'); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.returned'), 'no auto-rejected notice').toBe(false); + }); + }); + + describe('the reconciler', () => { + it('a parent run cancelled while its child\'s request is pending, which no door judged: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + await automation.cancelRun(String(child.record_run_id)); + await withoutDoor(() => settle(decide('i_cancel', 'approve', 'approver'))); + expect(await field('crm_invoice', 'i_cancel'), 'held: no door judged').toBe('pending'); + expect(await marks('i_cancel')).toEqual([true]); + + const out = await svc.reconcileMarkedApprovals(); + expect(out.judged).toEqual({ abandoned: 1 }); + expect(await steps('i_cancel')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel')).toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('a process that died between the last decision and the write of its outcome: written in the decider\'s name', async () => { + await start('two_step', 'crm_invoice', 'i_died'); + await decide('i_died', 'approve', 'approver'); + await withoutDoor(() => decide('i_died', 'approve', 'approver2')); + expect(await field('crm_invoice', 'i_died')).toBe('pending'); + expect(await marks('i_died')).toEqual([false, true]); + + const writes = recordWrites('crm_invoice'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([['approved', 'approver2']]); + expect(await field('crm_invoice', 'i_died')).toBe('approved'); + expect(await marks('i_died')).toEqual([false, false]); + }); + + it('a refused outcome is tried again while the mark stands, noted once and told under one key', async () => { + await start('two_step', 'crm_invoice', 'i_refuse'); + await decide('i_refuse', 'approve', 'approver'); + await withoutDoor(() => decide('i_refuse', 'approve', 'approver2')); + const original = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + (svc as any).organizationAdministrators = async () => ({ ids: ['org_admin'] }); + const keys: unknown[] = []; + svc.attachMessaging({ emit: async (n: any) => { if (n.topic === 'approval.status_mirror_refused') keys.push([n.audience, n.dedupKey]); } } as any); + await svc.reconcileMarkedApprovals(); + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('pending'); + expect(await marks('i_refuse')).toEqual([false, true]); + const [, last] = await requestsOn('i_refuse'); + // The notice is keyed per request and status, so the messaging service sends it once. + expect(keys).toEqual([[['org_admin'], `approval-mirror-refused-${last.id}-approved`], [['org_admin'], `approval-mirror-refused-${last.id}-approved`]]); + const lines = (await timeline(String(last.id))).filter(([, actor, text]) => actor === null && /could not|NOT|refused/i.test(String(text))); + expect(lines, 'the refusal is noted on the timeline once').toHaveLength(1); + + refuse = false; + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('approved'); + expect(await marks('i_refuse')).toEqual([false, false]); + }); + + it('an approval whose field the object does not close on: the hold ends, the mark is cleared and nothing is written', async () => { + await start('two_step', 'crm_ticket', 't_died'); + await decide('t_died', 'approve', 'approver'); + await withoutDoor(() => decide('t_died', 'approve', 'approver2')); + expect(await field('crm_ticket', 't_died'), 'written at once, as on main').toBe('approved'); + expect(await marks('t_died')).toEqual([false, true]); + + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([]); + expect(await marks('t_died')).toEqual([false, false]); + }); + + it('a record deleted in a passage: the marks are cleared once, with nothing written and no notice', async () => { + await start('two_step', 'crm_invoice', 'i_gone'); + await decide('i_gone', 'approve', 'approver'); + await withoutDoor(() => decide('i_gone', 'approve', 'approver2')); + await ql.delete('crm_invoice', { where: { id: 'i_gone' }, context: SYS } as any); + expect(await read('crm_invoice', 'i_gone')).toBeUndefined(); + notices.length = 0; + + const out = await svc.reconcileMarkedApprovals(); + expect(out.deletedRecords).toBe(1); + expect(out.judged).toEqual({}); + expect(await marks('i_gone')).toEqual([false, false]); + expect(notices).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'cleared once: not scanned again').toBe(0); + }); + + it('past the age bound, a run that reports paused while its pause is gone stopped where it stood: abandoned', async () => { + await start('two_step', 'crm_invoice', 'i_lost'); + const [first] = await requestsOn('i_lost'); + // The shape a process that died after the decision's row landed and as + // its run's pause was consumed leaves: decided, marked, and a run that + // reports paused with no pause. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + expect((await automation.getRun(runId))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('pending'); + expect(await marks('i_lost')).toEqual([true]); + + await age('i_lost'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/reports paused at a pause that is gone, so it will not go on, between two steps\./); + expect(await marks('i_lost')).toEqual([false]); + }); + + it('past the age bound, a run parked at a subflow whose child has ended, which nothing will resume: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_orphan'); + const [child] = await requestsOn('i_orphan'); + // The child's step was decided and its run ended, and the parent was never resumed. + await ql.update('sys_approval_request', { id: child.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + await automation.cancelRun(String(child.flow_run_id)); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the parent is parked between two steps').toEqual({ in_progress: 1 }); + expect(await marks('i_orphan')).toEqual([true]); + + await age('i_orphan'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_orphan')).toBe('recalled'); + expect((await timeline(String(child.id))).at(-1)![2]).toMatch(/parked at 'sub' on a child run that has ended, so nothing will resume it, between two steps\./); + expect(await marks('i_orphan')).toEqual([false]); + }); + + it('scans the oldest mark first, and at most its limit in each of its two windows', async () => { + for (const id of ['i_a', 'i_b']) { + await start('two_step', 'crm_invoice', id); + await decide(id, 'approve', 'approver'); + await withoutDoor(() => decide(id, 'approve', 'approver2')); + } + await age('i_b'); + const out = await svc.reconcileMarkedApprovals({ limit: 1 }); + expect(out.scanned).toBeLessThanOrEqual(2); + expect(await field('crm_invoice', 'i_b'), 'the older mark').toBe('approved'); + }); + + it('the stranded-request report leaves a stamped request to the reconciler, and still reports an unstamped one', async () => { + throwOn.add('boom'); + await start('boom_between', 'crm_invoice', 'i_report'); + await settle(decide('i_report', 'approve', 'approver')); + await start('boom_between', 'crm_memo', 'm_report'); + await settle(decide('m_report', 'approve', 'approver')); + const [stamped] = await requestsOn('i_report'); + const [unstamped] = await requestsOn('m_report'); + expect((await automation.getRun(String(stamped.flow_run_id)))?.status).toBe('failed'); + expect(stamped.between_steps_json).toBeTruthy(); + expect(unstamped.between_steps_json ?? null).toBeNull(); + const reported = (await svc.inspectStrandedRequests()).stranded.map((r: any) => String(r.requestId)); + expect(reported).toContain(String(unstamped.id)); + expect(reported).not.toContain(String(stamped.id)); + + // [S4] A returned request of a stamped approval (a send-back sets no + // mark, and no judgement places it) is reported as before. + await ql.update('sys_approval_request', { id: stamped.id, status: 'returned' }, { context: SYS }); + const again = (await svc.inspectStrandedRequests()).stranded.map((r: any) => String(r.requestId)); + expect(again).toContain(String(stamped.id)); + }); + + it('[S2] marks that stay cannot hold the head of the scan: a newer approval is still judged', async () => { + // Two approvals that stay in progress, oldest, and a newer one that a process left unjudged. + for (const id of ['i_hold_a', 'i_hold_b']) { + await start('sub_then_second', 'crm_invoice', id); + const [child] = await requestsOn(id); + await ql.update('sys_approval_request', { id: child.id, status: 'approved', unjudged_since: new Date(Date.now() - 1000).toISOString() }, { context: SYS }); + } + await start('two_step', 'crm_invoice', 'i_new'); + await decide('i_new', 'approve', 'approver'); + await withoutDoor(() => decide('i_new', 'approve', 'approver2')); + for (let pass = 0; pass < 3 && (await field('crm_invoice', 'i_new')) !== 'approved'; pass++) { + await svc.reconcileMarkedApprovals({ limit: 1 }); + } + expect(await field('crm_invoice', 'i_new')).toBe('approved'); + expect(await marks('i_hold_a'), 'still in progress').toEqual([true]); + }); + }); + + describe('the rulings on #37767 piece 4 (A3 and B2: one rule), and the fixes of 7255916895', () => { + /** Runs whose history the engine no longer holds: `getRun` answers no row. */ + let trimmed: Set; + let storeDown: Set; + beforeEach(() => { + trimmed = new Set(); + storeDown = new Set(); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (storeDown.has(id)) { + if (options?.strict) throw new Error('the run store did not answer'); + return null; + } + return trimmed.has(id) ? null : original(id, options); + }; + (svc as any).organizationAdministrators = async () => ({ ids: ['org_admin'] }); + }); + /** The decision is recorded, and the process stops before the run is resumed. */ + const withoutResume = async (fn: () => Promise): Promise => { + const resume = (svc as any).resumeRecordedOutcome; + (svc as any).resumeRecordedOutcome = async () => { throw new Error('the process stopped'); }; + try { return await fn(); } finally { (svc as any).resumeRecordedOutcome = resume; } + }; + const kept = (r: any) => JSON.parse(String(r.node_config_json ?? '{}')).__runsRead; + const notified = (topic: string) => notices.filter((n) => n.topic === topic).map((n) => n.audience); + + it('[M1] a subflow its child flow skipped names no run, and the approval finishes at the door', async () => { + await start('gated_sub_between', 'crm_invoice', 'i_gated'); + await decide('i_gated', 'approve', 'approver'); + await decide('i_gated', 'approve', 'approver2'); + const [first] = await requestsOn('i_gated'); + const root: any = await automation.getRun(String(first.record_run_id)); + expect(root.steps.find((s: any) => s.nodeId === 'gate').childRunIds).toBeUndefined(); + expect(await field('crm_invoice', 'i_gated')).toBe('approved'); + expect(await marks('i_gated')).toEqual([false, false]); + }); + + it('[M3] a failure between two steps routed to a pause no step follows: abandoned, not finished', async () => { + await start('routed_to_wait', 'crm_invoice', 'i_wait'); + throwOn.add('boom'); + await decide('i_wait', 'approve', 'approver'); + const [first] = await requestsOn('i_wait'); + expect((await automation.getRun(String(first.flow_run_id)))?.status, 'parked at the pause').toBe('paused'); + expect(await steps('i_wait')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_wait')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + }); + + it('[S3] a map item run that holds no request, whose node failed before its step: abandoned', async () => { + await start('first_then_items', 'crm_invoice', 'i_items'); + throwOn.add('boom'); + await decide('i_items', 'approve', 'approver'); + expect(await steps('i_items')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_items')).toBe('recalled'); + }); + + it('[A3] a child that ended before the first step is kept as read: its trimmed history does not hold the approval', async () => { + await start('early_sub_two_step', 'crm_invoice', 'i_early'); + const [first] = await requestsOn('i_early'); + const root: any = await automation.getRun(String(first.record_run_id)); + const child = String(root.steps.find((s: any) => s.nodeId === 'prep').childRunIds[0]); + await decide('i_early', 'approve', 'approver'); + const [, second] = await requestsOn('i_early'); + expect(kept(second)?.ended, 'kept as the next request opened').toContain(child); + trimmed.add(child); + await decide('i_early', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_early'), 'written at the door').toBe('approved'); + expect(await marks('i_early')).toEqual([false, false]); + }); + + it('[A3] a refused outcome tried again after the run that carries the record was trimmed: written, not held', async () => { + await start('two_step', 'crm_invoice', 'i_retry'); + await decide('i_retry', 'approve', 'approver'); + const original = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + await decide('i_retry', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_retry')).toBe('pending'); + const [, last] = await requestsOn('i_retry'); + expect(kept(last)?.ended, 'the door kept the run it read to its end').toContain(String(last.record_run_id)); + trimmed.add(String(last.record_run_id)); + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_retry')).toBe('approved'); + }); + + it('[A3] a run with no row after the last decision: within the bound held, past it written, and the administrators are told', async () => { + await start('two_step', 'crm_invoice', 'i_norow'); + await decide('i_norow', 'approve', 'approver'); + await withoutDoor(() => decide('i_norow', 'approve', 'approver2')); + const [, last] = await requestsOn('i_norow'); + trimmed.add(String(last.record_run_id)); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_norow')).toBe('pending'); + expect(await marks('i_norow')).toEqual([false, true]); + + await age('i_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_norow'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_norow')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[A3] a run with no row after a step a later step follows: past the bound, abandoned', async () => { + await start('two_step', 'crm_invoice', 'i_norow_mid'); + await settle(withoutResume(() => decide('i_norow_mid', 'approve', 'approver'))); + const [first] = await requestsOn('i_norow_mid'); + trimmed.add(String(first.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + await age('i_norow_mid'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, and the judgement before read the same').toEqual({ abandoned: 1 }); + expect(await steps('i_norow_mid'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_norow_mid')).toBe('recalled'); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect(notified('approval.flow_not_continued')).toEqual([]); + }); + + it('[A3] a store that does not answer is not a run with no row: held at any age', async () => { + await start('two_step', 'crm_invoice', 'i_down'); + await decide('i_down', 'approve', 'approver'); + await withoutDoor(() => decide('i_down', 'approve', 'approver2')); + const [, last] = await requestsOn('i_down'); + storeDown.add(String(last.record_run_id)); + await age('i_down'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_down')).toBe('pending'); + expect(await marks('i_down')).toEqual([false, true]); + }); + + it('[B2] a decision whose run was never resumed, at a step a later step follows: past the bound abandoned, and the run cancelled', async () => { + await start('two_step', 'crm_invoice', 'i_parked'); + await settle(withoutResume(() => decide('i_parked', 'approve', 'approver'))); + const [first] = await requestsOn('i_parked'); + expect((await automation.getRun(String(first.flow_run_id)))?.status).toBe('paused'); + expect(await field('crm_invoice', 'i_parked'), 'held at the door').toBe('pending'); + expect(await marks('i_parked')).toEqual([true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the run may still be resumed').toEqual({ undetermined: 1 }); + expect(await marks('i_parked')).toEqual([true]); + + await age('i_parked'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_parked'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_parked')).toBe('recalled'); + expect(await marks('i_parked')).toEqual([false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect((await automation.getRun(String(first.flow_run_id)))?.status, 'nothing resumes it').toBe('cancelled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/still parked at the step 'first' its decision was recorded on/); + }); + + it('[B2] a decision whose run was never resumed, at the last step: past the bound written, the administrators told, and the pause left', async () => { + await start('two_step', 'crm_invoice', 'i_parked_last'); + await decide('i_parked_last', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_parked_last', 'approve', 'approver2'))); + const [, last] = await requestsOn('i_parked_last'); + expect(await field('crm_invoice', 'i_parked_last'), 'held at the door').toBe('pending'); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_parked_last'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_parked_last')).toBe('approved'); + expect(await marks('i_parked_last')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + expect(notified('approval.abandoned')).toEqual([]); + expect((await automation.getRun(String(last.flow_run_id)))?.status, 'the pause is left for an operator').toBe('paused'); + }); + + describe('the rebuild on contract review 7257527251: the kept reading is safe to judge from', () => { + /** Flows whose runs have no row from the start: trimmed before the plugin read them. */ + let trimmedFlows: Set; + /** Flows for whose runs the run store does not answer. */ + let downFlows: Set; + beforeEach(() => { + trimmedFlows = new Set(); + downFlows = new Set(); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await original(id, options); + const name = String(run?.flowName ?? ''); + if (run && downFlows.has(name)) { + if (options?.strict) throw new Error('the run store did not answer'); + return null; + } + return run && trimmedFlows.has(name) ? null : run; + }; + }); + const statusOf = async (runId: unknown) => (await automation.getRun(String(runId)))?.status; + const lastLine = async (requestId: unknown) => String((await timeline(String(requestId))).at(-1)![2]); + /** The summary the engine folds from a whole step log: one execution for each step. */ + const folded = (steps: any[]) => ({ + selected: 0, acted: 0, skipped: 0, + nodes: steps.map((s) => ({ nodeId: s.nodeId, nodeType: s.nodeType ?? 'script', status: 'success', runs: 1, failures: 0, skipped: 0 })), + }); + /** Refuse the mirror's write of `approved` on the invoice while `on()` holds. */ + const refuseApproved = (on: () => boolean) => { + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (on() && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + }; + + it('[M4] a sibling child whose read threw at the door is read on the next pass: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_m4_throw'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_throw', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_throw'); + expect(await statusOf(first.record_run_id), 'the carrying run completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_throw'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m4_throw')).toEqual([true]); + + downFlows.clear(); + expect((await svc.reconcileMarkedApprovals()).judged, 'the store answers now: the sibling is read').toEqual({ abandoned: 1 }); + expect(await steps('i_m4_throw'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_m4_throw')).toBe('recalled'); + expect(await lastLine(first.id)).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_m4_throw')).toEqual([false]); + }); + + it('[M4] a child with no row under a run that ended at its step: nothing is written within the bound on any pass; past it, the one rule and the notice', async () => { + await start('fail_after_last', 'crm_invoice', 'i_m4_norow'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await settle(decide('i_m4_norow', 'approve', 'approver')); + const [only] = await requestsOn('i_m4_norow'); + expect(await statusOf(only.record_run_id), 'the run failed at the child\'s step').toBe('failed'); + expect(await field('crm_invoice', 'i_m4_norow'), 'the door cannot tell').toBe('pending'); + notices.length = 0; + + for (const pass of ['the next pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), pass).toBe('pending'); + expect(await marks('i_m4_norow'), pass).toEqual([true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + + await age('i_m4_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m4_norow')).toEqual([false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M4] past the 200 runs one judgement reads: cannot tell, and the next pass reads on to the failure the first never reached', async () => { + await start('two_step', 'crm_invoice', 'i_m4_cap'); + await decide('i_m4_cap', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_cap', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_cap'); + const rootId = String(last.record_run_id); + // A double of the run store for a tree the engine does not build + // cheaply: the run that carries the record names 250 child runs, each + // completed, and the last holds a failure the flow routed between two + // steps (matched by its node id, as a run of an unknown flow is). + const fan = Array.from({ length: 250 }, (_, i) => `run_fan_${i}`); + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: fan }] }; + } + const i = fan.indexOf(id); + if (i < 0) return real(id, options); + const steps = i === fan.length - 1 ? [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] : []; + return { + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: 'i_m4_cap' }, steps, summary: folded(steps), + }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first 200 runs').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('pending'); + expect(await marks('i_m4_cap')).toEqual([false, true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'the runs past them').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + + it('[M4] a run in progress beside a sibling that failed: in progress, and once it has ended the sibling still counts', async () => { + await start('two_step', 'crm_invoice', 'i_m4_wait'); + await decide('i_m4_wait', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_wait', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_wait'); + const rootId = String(last.record_run_id); + // A double of the run store, as in the case of the 200 runs: the run + // that carries the record names two child runs. The first is parked + // between two steps (matched by its node id, as a run of an unknown + // flow is); the second ended with a failure the flow routed there. + const at = new Date().toISOString(); + const child = { flowName: 'fan_child', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m4_wait' } }; + let waiting = true; + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_wait', 'run_done'] }] }; + } + if (id === 'run_wait') { + return waiting ? { id, ...child, status: 'paused', steps: [] } : { id, ...child, status: 'completed', completedAt: at, steps: [], summary: folded([]) }; + } + if (id === 'run_done') { + const steps = [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }]; + return { id, ...child, status: 'completed', completedAt: at, steps, summary: folded(steps) }; + } + return real(id, options); + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === 'run_wait' + ? (waiting ? { nodeId: 'first', flowName: 'fan_child' } : undefined) + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'a run is parked between two steps').toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('pending'); + + waiting = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'it ended: the sibling that failed is not skipped').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + + it('[M4] a run read to its end over a child not read yet, whose own row is gone by the next pass, is not taken as passed', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_m4_owed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_owed', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_owed'); + expect(await statusOf(first.record_run_id), 'the root went on past the middle run and completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_owed'), 'the door cannot tell').toBe('pending'); + + // The store answers again, and the middle run's row is gone: the + // root's log says it went on past it, but the plugin read that run + // and knows a child of it was never read. + downFlows.clear(); + trimmedFlows.add('parent_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('pending'); + expect(await marks('i_m4_owed')).toEqual([true]); + + await age('i_m4_owed'); + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by the step last decided, which a step can follow').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('recalled'); + }); + + it('[S1] a decision in a child run whose parent is parked at its subflow between two steps: held within the bound, past it abandoned, and both runs cancelled', async () => { + await start('sub_then_second', 'crm_invoice', 'i_s1'); + await settle(withoutResume(() => decide('i_s1', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1'); + expect(String(child.flow_run_id)).not.toBe(String(child.record_run_id)); + expect(await statusOf(child.flow_run_id), 'the child is parked at its decided step').toBe('paused'); + expect(await statusOf(child.record_run_id), 'the parent is parked at its subflow').toBe('paused'); + expect(await field('crm_invoice', 'i_s1'), 'held at the door').toBe('pending'); + expect(await marks('i_s1')).toEqual([true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the run may still be resumed').toEqual({ undetermined: 1 }); + expect(await marks('i_s1')).toEqual([true]); + + await age('i_s1'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_s1'), 'the decision stays on its request').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_s1')).toBe('recalled'); + expect(await marks('i_s1')).toEqual([false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect(await lastLine(child.id)).toMatch(/still parked at the step 'only' its decision was recorded on/); + expect(await statusOf(child.flow_run_id), 'nothing resumes the child').toBe('cancelled'); + expect(await statusOf(child.record_run_id), 'nor the parent that waited on it').toBe('cancelled'); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S1] the same two levels down: the walk reaches the decided step through both parked runs', async () => { + await start('root_mid_then_second', 'crm_invoice', 'i_s1_deep'); + await settle(withoutResume(() => decide('i_s1_deep', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1_deep'); + const root: any = await automation.getRun(String(child.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(child.flow_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_s1_deep'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s1_deep')).toBe('recalled'); + expect(await marks('i_s1_deep')).toEqual([false]); + expect([await statusOf(child.flow_run_id), await statusOf(middle), await statusOf(child.record_run_id)]).toEqual(['cancelled', 'cancelled', 'cancelled']); + }); + + it('[S1, N8] the same under a map whose items are not records: the batch above the item run is cancelled with it, and no later item opens', async () => { + await start('first_then_two_items', 'crm_invoice', 'i_n8'); + await decide('i_n8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_n8', 'approve', 'approver2'))); + const [, item] = await requestsOn('i_n8'); + expect(String(item.flow_run_id)).not.toBe(String(item.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_n8'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n8')).toBe('recalled'); + expect(await statusOf(item.flow_run_id), 'the item run').toBe('cancelled'); + expect(await statusOf(item.record_run_id), 'the batch that waited on it').toBe('cancelled'); + expect(await steps('i_n8'), 'the second item\'s step never opens on a record that was put back').toEqual([['first', 'approved'], ['second', 'approved']]); + }); + + it('[S7 point 1] a door that leaves the next request pending still reads the runs it can reach, and keeps them', async () => { + await start('sub_between', 'crm_invoice', 'i_s7_door'); + await decide('i_s7_door', 'approve', 'approver'); + const [first, second] = await requestsOn('i_s7_door'); + expect(second.status).toBe('pending'); + const root: any = await automation.getRun(String(first.record_run_id)); + const child = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + // The child ended inside the passage: no opening could read it (the + // run that was being advanced had not logged its step yet), and the + // door that left the second request pending did. + expect(kept(second)?.ended, 'kept at the door').toContain(child); + }); + + it('[S7 point 2] a child whose row is gone before any read, under a run that went on past its step, is passed: finished at the door, with no notice', async () => { + trimmedFlows.add('child_noop'); + await start('early_sub_two_step', 'crm_invoice', 'i_s7_passed'); + await decide('i_s7_passed', 'approve', 'approver'); + notices.length = 0; + await decide('i_s7_passed', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_s7_passed'), 'written at the door').toBe('approved'); + expect(await marks('i_s7_passed')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S7, the failure route] a run that went on along a fault edge did not go on past the step: its child with no row is held, then placed', async () => { + await start('fault_after_last', 'crm_invoice', 'i_s7_fault'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await decide('i_s7_fault', 'approve', 'approver'); + const [only] = await requestsOn('i_s7_fault'); + const root: any = await automation.getRun(String(only.record_run_id)); + expect(root.status, 'the failure was routed, and the run completed').toBe('completed'); + expect(root.steps.find((s: any) => s.nodeId === 'sub').status).toBe('failure'); + expect(await field('crm_invoice', 'i_s7_fault'), 'not passed: the door cannot tell').toBe('pending'); + expect(await marks('i_s7_fault')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('pending'); + + await age('i_s7_fault'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S7 point 2, its edge] a run still parked at the step that names a child did not go on past it, whatever it logged after', async () => { + await start('two_step', 'crm_invoice', 'i_s7_parked'); + await decide('i_s7_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s7_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s7_parked'); + const rootId = String(last.record_run_id); + // A double of the run store for a shape the engine logs in an order + // a fixture cannot fix: after the last step the run is parked at a + // `subflow` no step follows, on a child with no row, and a step on + // another branch of the flow was logged after the visit that parked it. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_tail_child') return null; + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + return { + ...run, status: 'paused', completedAt: undefined, + steps: [...run.steps, + { nodeId: 'tail_sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_tail_child'] }, + { nodeId: 'tail_note', nodeType: 'script', status: 'success', startedAt: at }], + }; + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === rootId + ? { nodeId: 'tail_sub', flowName: 'two_step', correlation: 'subflow:run_tail_child' } + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: no run speaks for the child').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('pending'); + expect(await marks('i_s7_parked')).toEqual([false, true]); + + await age('i_s7_parked'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'the one rule, with its notice').toEqual([['org_admin']]); + }); + + it('[M5] a map step that started more item runs than it names: cannot tell, held to the bound and then placed; its log speaks for no run it names', async () => { + await start('two_step', 'crm_invoice', 'i_m5_trunc'); + await decide('i_m5_trunc', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_trunc', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_trunc'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went through + // a `map` whose step carries the engine's mark that it started more + // item runs than it names (`childRunIdsTruncated`, ruling 7258590209), + // and on to its end. One of the two item runs it names has no row. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_item_gone') return null; + if (id === 'run_item_0') { + return { id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m5_trunc' }, steps: [], summary: folded([]) }; + } + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + const steps = [...run.steps, + { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIds: ['run_item_0', 'run_item_gone'], childRunIdsTruncated: true }, + { nodeId: 'tail', nodeType: 'script', status: 'success', startedAt: at }]; + return { ...run, steps, summary: folded(steps) }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the item runs the step does not name cannot be read').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('pending'); + expect(await marks('i_m5_trunc')).toEqual([false, true]); + const read = kept((await requestsOn('i_m5_trunc')).at(-1)); + expect(read.ended, 'a truncated step does not speak for an item run with no row').not.toContain('run_item_gone'); + expect(read.ended, 'and its run is not done with').not.toContain(rootId); + expect(read.open).toContain(rootId); + + await age('i_m5_trunc'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + }); + + it.each([ + ['cut short', 'cut', (steps: any[]) => steps.slice(1)], + ['stored as null', 'null', () => [] as any[]], + ])('[M5] a step log the history row %s: cannot tell, held to the bound and then placed', async (_how, tag, stored) => { + const id = `i_m5_${tag}`; + await start('two_step', 'crm_invoice', id); + await decide(id, 'approve', 'approver'); + await withoutDoor(() => decide(id, 'approve', 'approver2')); + const [, last] = await requestsOn(id); + const rootId = String(last.record_run_id); + // The run's summary still counts every step it logged; the row keeps fewer. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (runId: string, options?: { strict?: boolean }) => { + const run: any = await real(runId, options); + return runId === rootId && run ? { ...run, steps: stored(run.steps), summary: folded(run.steps) } : run; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', id)).toBe('pending'); + expect(await marks(id)).toEqual([false, true]); + + await age(id); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', id)).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S6] a note another writer leaves on the request between the reading and the kept write survives it', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_s6'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + const original = ql.update.bind(ql); + let landed = false; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (!landed && o === 'sys_approval_request' && typeof data?.node_config_json === 'string' && data.node_config_json.includes('"__runsRead"')) { + landed = true; + // The kept reading is on its way to the row. Before it lands, + // another writer puts its notes on the same snapshot. + const [row] = await requestsOn('i_s6'); + await original('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'second', at: new Date().toISOString(), reason: 'no approver' }, + __strandedContinuation: { decision: 'approve' }, + }), + }, { context: SYS }); + } + return original(o, data, options); + }; + await decide('i_s6', 'approve', 'approver'); + expect(landed, 'the door kept what it read').toBe(true); + const [row] = await requestsOn('i_s6'); + const snapshot = JSON.parse(String(row.node_config_json)); + expect(snapshot.__laterStepNotOpened?.node, 'the note that a later step could not open').toBe('second'); + expect(snapshot.__strandedContinuation, 'the journal of a failed resume').toEqual({ decision: 'approve' }); + expect(snapshot.__runsRead?.ended, 'and the reading is kept beside them').toContain(String(row.flow_run_id)); + }); + + it('[S6] a note that lands while the runs are being read is the judgement\'s: abandoned, not finished', async () => { + await start('two_step', 'crm_invoice', 'i_s6_late'); + await decide('i_s6_late', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + let landed = false; + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (!landed && options?.strict) { + landed = true; + // The judgement has read the request and is reading its runs. + // The passage of another process notes that the step after the + // last decision could not open, as `noteLaterStepNotOpened` does. + const row = (await requestsOn('i_s6_late')).at(-1)!; + await ql.update('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'third', at: new Date().toISOString(), reason: 'no approver' }, + }), + }, { context: SYS }); + } + return original(id, options); + }; + notices.length = 0; + await decide('i_s6_late', 'approve', 'approver2'); + expect(landed, 'the door read the runs').toBe(true); + expect(await steps('i_s6_late')).toEqual([['first', 'approved'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_s6_late'), 'a later step could not open: the record is not closed').toBe('recalled'); + expect(await marks('i_s6_late')).toEqual([false, false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + const last = (await requestsOn('i_s6_late')).at(-1)!; + expect(await lastLine(last.id)).toMatch(/its step 'third' could not open \(no approver\)/); + }); + + it('[S8] a refused outcome at a last step that was placed sends no notice that the flow did not go on; the pass on which the write lands sends it', async () => { + await start('two_step', 'crm_invoice', 'i_s8'); + await decide('i_s8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_s8', 'approve', 'approver2'))); + await age('i_s8'); + let refuse = true; + refuseApproved(() => refuse); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8'), 'the write was refused').toBe('pending'); + expect(await marks('i_s8')).toEqual([false, true]); + expect(notified('approval.status_mirror_refused'), 'the refusal is told').toEqual([['org_admin']]); + expect(notified('approval.flow_not_continued'), 'no outcome, no notice').toEqual([]); + + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8')).toBe('approved'); + expect(await marks('i_s8')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'with the outcome').toEqual([['org_admin']]); + }); + + it('[N9] where nothing was held back, a placed approval leaves a line in the log; nothing is written, told or cancelled', async () => { + await start('two_step', 'crm_ticket', 't_n9'); + await settle(withoutResume(() => decide('t_n9', 'approve', 'approver'))); + const [first] = await requestsOn('t_n9'); + await age('t_n9'); + infos.length = 0; + notices.length = 0; + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ ended: 1 }); + expect(await marks('t_n9')).toEqual([false]); + expect(writes).toEqual([]); + expect(notices).toEqual([]); + expect(await statusOf(first.flow_run_id), 'the pause is left').toBe('paused'); + expect(infos.filter((m) => m.includes('crm_ticket/t_n9')), 'what the reconciler concluded is in the log').toHaveLength(1); + }); + + describe('the rework on contract review 7266979193: a tree one judgement cannot read has an end, and a map of records is placed', () => { + const at = new Date().toISOString(); + /** A run of a double that reached its end, on the record `record`. */ + const ended = (id: string, record: string, steps: any[] = []) => ({ + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: record }, steps, summary: folded(steps), + }); + /** A `map` step that names the item runs `ids`. */ + const fan = (node: string, ids: string[]) => ({ nodeId: node, nodeType: 'map', status: 'success', startedAt: at, childRunIds: ids }); + const ids = (prefix: string) => Array.from({ length: 200 }, (_, i) => `${prefix}_${i}`); + /** + * A double of the run store over the real one, for trees the engine + * does not build cheaply: the run that carries the record logs + * `rootSteps` after its own (and reads as `root` says), and `runs` + * answers for the runs those steps name. + */ + const tree = (rootId: string, rootSteps: any[], runs: (id: string) => unknown, root: Record = {}) => { + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, ...root, steps: [...run.steps, ...rootSteps] }; + } + const run = runs(id); + return run === undefined ? real(id, options) : run; + }; + }; + /** An item run that is not a record's, and called a `subflow`; and the run that `subflow` started. */ + const itemsThatDelegate = (record: string) => (id: string) => { + const [, kind, i] = /^run_(item|below)_(\d+)$/.exec(id) ?? []; + if (kind === 'item') return ended(id, record, [{ nodeId: 'sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: [`run_below_${i}`] }]); + return kind === 'below' ? ended(id, record) : undefined; + }; + const keptOn = async (id: string) => kept((await requestsOn(id)).at(-1)); + /** The item run the batch of `first_then_records` waits on. */ + const itemOf = async (batch: string) => String((await automation.suspensionOf(batch))?.correlation ?? '').replace(/^map:/, ''); + const seedLines = async () => { for (const id of ['m_line_1', 'm_line_2']) await seed('crm_memo', id); }; + + it('[S11] a map of 200 items that are not records, each calling a subflow: no judgement can keep a run, so the approval is held within the bound and placed past it', async () => { + await start('two_step', 'crm_invoice', 'i_s11_deep'); + await decide('i_s11_deep', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_deep', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_deep'); + // After the last step the run went through a `map` of 200 items + // that are not records, and on to its end; each item run called a + // `subflow`. One judgement reads the run and 199 item runs, and no + // run an item started: no run is read to its end with every run + // below it, so nothing is kept as ended, on any pass. + tree(String(last.record_run_id), [fan('fan', ids('run_item'))], itemsThatDelegate('i_s11_deep')); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), pass).toBe('pending'); + expect(await marks('i_s11_deep'), pass).toEqual([false, true]); + } + expect((await keptOn('i_s11_deep')).ended, 'no run was read to its end with every run below it').toEqual([]); + + await age('i_s11_deep'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: a tree the walk cannot finish is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_s11_deep')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S11] two map steps of 200 record items after the decision: past the bound the judgements read on while each keeps more runs, and the one that can keep no more places the approval', async () => { + await start('two_step', 'crm_invoice', 'i_s11_wide'); + await decide('i_s11_wide', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_wide', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_wide'); + // After the last step the run went through two `map` steps of 200 + // items each, every item a record of its own, and on to its end: + // 401 runs, where one judgement reads 200 and the kept list holds 200. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + // No door judged, and the first judgement comes past the bound. + await age('i_s11_wide'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps 199 item runs, so the next judgement reads on').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(199); + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps one more, and the kept list is full').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(200); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('pending'); + expect(notified('approval.flow_not_continued')).toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'it can keep no more: the tree cannot be finished, and is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('approved'); + expect(await marks('i_s11_wide')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] a parked run whose child the judgement did not get to says nothing: the tree is placed all the same', async () => { + await start('two_step', 'crm_invoice', 'i_s11_parked'); + await decide('i_s11_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_parked'); + const rootId = String(last.record_run_id); + // The tree of the first case, still in flight: after its last step + // the run is parked at the `map` (a node no step follows) on item + // 198, and that item run is parked between two steps (matched by + // its node id, as a run of an unknown flow is) on a child run. One + // judgement reads the run and items 0 to 198, and not that child. + const delegating = itemsThatDelegate('i_s11_parked'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_item_198' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_parked' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'fan', flowName: 'two_step', correlation: 'map:run_item_198' }; + return id === 'run_item_198' ? { nodeId: 'first', flowName: 'fan_child', correlation: 'subflow:run_waited_on' } : parkedAt(id); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await marks('i_s11_parked')).toEqual([false, true]); + + await age('i_s11_parked'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: placed, not in progress for good').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_parked')).toBe('approved'); + expect(await marks('i_s11_parked')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] a reading that cannot be kept does not read on: past the bound the approval is placed at once', async () => { + await start('two_step', 'crm_invoice', 'i_s11_unkept'); + await decide('i_s11_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_unkept'); + // The tree of two map steps, whose first reading keeps 199 item runs. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the tree is too large to read, and what was read is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_unkept')).ended).toHaveLength(199); + await age('i_s11_unkept'); + // From here the store refuses the kept reading, on every try: a + // judgement that reads on would find the next one where it is itself. + const update = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'what it read is not on the request, so it does not wait for a next reading').toEqual({ finished: 1 }); + expect((await keptOn('i_s11_unkept')).ended, 'the one run more it read to its end was not kept').toHaveLength(199); + expect(await field('crm_invoice', 'i_s11_unkept')).toBe('approved'); + expect(await marks('i_s11_unkept')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] the child a parked run waits on is read before the runs beside it: in a tree too large to read, a child that is in progress still says so', async () => { + await start('two_step', 'crm_invoice', 'i_s11_live'); + await decide('i_s11_live', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_live', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_live'); + const rootId = String(last.record_run_id); + // The run that carries the record is parked between two steps on a + // child run, after a `map` of 200 items that each called a + // `subflow`; the child it waits on is parked between two steps in + // its own right (matched by its node id, as a run of an unknown + // flow is). No step names that child, so the walk learns of it + // from the pause alone. + const delegating = itemsThatDelegate('i_s11_live'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_waited_on' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_live' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'first', flowName: 'two_step', correlation: 'subflow:run_waited_on' }; + return id === 'run_waited_on' ? { nodeId: 'first', flowName: 'fan_child' } : parkedAt(id); + }; + await age('i_s11_live'); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, past the bound`).toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_s11_live'), pass).toBe('pending'); + expect(await marks('i_s11_live'), pass).toEqual([false, true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + }); + + it('[S12] a run parked at a map whose items are records, on an item run that has ended: past the bound nothing will resume it, and the approval is over', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12'); + // The first step is decided, and the batch starts its first item, + // whose step is an approval of the item's own record. No door + // judges: the process stops there. + await withoutDoor(() => decide('t_s12', 'approve', 'approver')); + const [first] = await requestsOn('t_s12'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + expect((await automation.getRun(item) as any)?.trigger, 'the item run carries a record of its own').toMatchObject({ object: 'crm_memo', recordId: 'm_line_1' }); + // The item run ends, and nothing resumes the batch. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the engine may still be resuming the batch').toEqual({ in_progress: 1 }); + expect(await marks('t_s12')).toEqual([true]); + + await age('t_s12'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the batch is parked between two steps on a run that has ended, as the judgement before read it').toEqual({ ended: 1 }); + expect(await marks('t_s12'), 'the ticket closes on another field, so nothing was held back: the hold ends').toEqual([false]); + expect(await steps('t_s12'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S12] an item run that has not ended is not kept as ended: the batch waits on it past the bound, and goes on when the item is decided', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12_live'); + await decide('t_s12_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s12_live'); + const item = await itemOf(String(first.record_run_id)); + expect(await statusOf(item), 'the item waits for its own approval').toBe('paused'); + // The door read the item run: it carries another record, and it has not ended. + expect(kept(first)?.ended ?? [], 'not kept as ended').not.toContain(item); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ in_progress: 1 }); + + await age('t_s12_live'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, the item is still being approved').toEqual({ in_progress: 1 }); + expect(await marks('t_s12_live')).toEqual([true]); + + // Each item's own approval is decided: the batch goes on to the next item, and after the last to the second step. + await decide('m_line_1', 'approve', 'approver'); + await decide('m_line_2', 'approve', 'approver'); + expect(await steps('t_s12_live')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(kept((await requestsOn('t_s12_live')).at(-1))?.ended, 'an item run that ended is kept').toContain(item); + }); + + it('[S12] as a request opens, an item run of another record that has not ended is not kept as ended either', async () => { + await start('two_step', 'crm_invoice', 'i_s12_open'); + const [first] = await requestsOn('i_s12_open'); + // A double of the run store: before its second step the run went + // through a `map` whose one item is a record of its own, and that + // item run has not ended. + tree(String(first.record_run_id), [fan('each', ['run_of_a_line'])], (id) => (id === 'run_of_a_line' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_memo', recordId: 'm_line_9' }, steps: [] } + : undefined)); + + // The second step opens, and its request keeps what the plugin can read; the door then reads again. + await decide('i_s12_open', 'approve', 'approver'); + const [, second] = await requestsOn('i_s12_open'); + expect(second.status).toBe('pending'); + expect(kept(second)?.ended ?? [], 'neither the opening nor the door kept it').not.toContain('run_of_a_line'); + }); + + it('[N20] the step last decided is placed in its own flow: a node of another flow of the set that carries its id does not answer for it', async () => { + await start('gate_sub_final', 'crm_invoice', 'i_n20'); + await decide('i_n20', 'approve', 'approver'); + await withoutDoor(() => decide('i_n20', 'approve', 'approver2')); + const [, last] = await requestsOn('i_n20'); + expect(await statusOf(last.record_run_id), 'the run went on to its end').toBe('completed'); + // The set names the child's node `final`, which stands between the + // two steps, and not the parent's step of that id, which is the last. + const stamp = JSON.parse(String(last.between_steps_json)); + expect(stamp).toContainEqual({ flow: 'child_named_final', node: 'final' }); + expect(stamp).not.toContainEqual({ flow: 'gate_sub_final', node: 'final' }); + expect(last.process_name, 'the request records the flow its step stands in').toBe('flow:gate_sub_final'); + + // No door judged, and the run that carries the record has no row any more. + trimmed.add(String(last.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + await age('i_n20'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by its last step: no step can follow it').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_n20')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[N21] the number of steps the plugin takes the engine to keep of a long log is the engine\'s', () => { + expect(HISTORY_STEPS_KEPT).toBe(MAX_PERSISTED_HISTORY_STEPS); + }); + + it('[N22] the runs kept as open seed the next reading: a failure below one is found though the run above it has no row left', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_n22_seed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_n22_seed', 'approve', 'approver'); + const [first] = await requestsOn('i_n22_seed'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(await field('crm_invoice', 'i_n22_seed'), 'the door cannot tell').toBe('pending'); + expect([...kept(first).open].sort(), 'the root and the middle run ended over a child that was not read').toEqual([String(first.record_run_id), middle].sort()); + + // The store answers again, and the root's row is gone: only the + // kept reading still leads to the middle run and the child below it. + downFlows.clear(); + trimmedFlows.add('root_of_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the middle run is read from the kept reading').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n22_seed')).toBe('recalled'); + expect(await marks('i_n22_seed')).toEqual([false]); + }); + + it('[M5, N22] a marked step that carries no list, as a history row whose links were shed: cannot tell, held to the bound and then placed', async () => { + await start('two_step', 'crm_invoice', 'i_m5_shed'); + await decide('i_m5_shed', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_shed', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_shed'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went + // through a `map` whose step carries the engine's mark and no list. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await real(id, options); + if (id !== rootId || !run) return run; + const all = [...run.steps, { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIdsTruncated: true }]; + return { ...run, steps: all, summary: folded(all) }; + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('pending'); + expect((await keptOn('i_m5_shed')).ended, 'its run is not done with').not.toContain(rootId); + + await age('i_m5_shed'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M5, N21, N22] on the real engine, a map of 201 items: its step names as many item runs as one judgement reads and is marked, so the approval is held and then placed', async () => { + await start('only_then_fan', 'crm_invoice', 'i_m5_real'); + await decide('i_m5_real', 'approve', 'approver'); + const [only] = await requestsOn('i_m5_real'); + const rootId = String(only.record_run_id); + const root: any = await automation.getRun(rootId); + expect(root.status, 'the run went through the map to its end').toBe('completed'); + const fanStep = root.steps.find((s: any) => s.nodeId === 'fan'); + expect(fanStep.childRunIds, 'the engine names on one step as many child runs as one judgement reads').toHaveLength(MAX_RUNS_READ_PER_APPROVAL); + expect(fanStep.childRunIdsTruncated, 'and marks the step that started more').toBe(true); + expect(await field('crm_invoice', 'i_m5_real'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m5_real')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + const read = await keptOn('i_m5_real'); + expect(read.ended, 'every item run the step names was read to its end').toEqual(expect.arrayContaining(fanStep.childRunIds)); + expect(read.ended, 'the run that carries the record is not done with: the item run its step does not name was never read').not.toContain(rootId); + expect(await field('crm_invoice', 'i_m5_real')).toBe('pending'); + + await age('i_m5_real'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_real'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m5_real')).toEqual([false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + // 201 runs of the child flow through the real engine and its store: + // well over the default timeout on a loaded runner (12 s measured in CI). + }, 60_000); + + describe('the patch on delta review 7269135624: past the bound, a run is placed only once two judgements in a row read it the same', () => { + // An object that closes on its approval field admits no pause + // between two steps (the opening check refuses the flow), so the + // approvals that wait there by design are those that hold nothing + // back: a ticket, which closes on another field. + it('[S14] a run the engine is resuming past the bound is not placed: its approval waited longer than the bound between two steps, by design', async () => { + await start('wait_between', 'crm_ticket', 't_s14_live'); + await decide('t_s14_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_live'); + const runId = String(first.record_run_id); + expect((await automation.suspensionOf(runId))?.nodeId, 'parked at the wait, between the two steps').toBe('hold'); + expect(await marks('t_s14_live')).toEqual([true]); + // The wait outlasts the bound, and a sweep in that time reads the run as in progress. + await age('t_s14_live'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // The wait ends and the engine resumes the run. The sweep of + // another process reads the run inside that passage: its pause is + // consumed, and it has not parked again. + let inside: unknown; + during.set('probe', async () => { + const readAs = [(await automation.getRun(runId))?.status, (await automation.suspensionOf(runId))?.nodeId]; + const judged = (await svc.reconcileMarkedApprovals()).judged; + inside = { readAs, judged, marks: await marks('t_s14_live') }; + }); + await automation.resume(runId); + expect(inside, 'inside the passage the run reports paused with its pause gone, and the first judgement to read it so cannot tell').toEqual({ + readAs: ['paused', undefined], judged: { undetermined: 1 }, marks: [true], + }); + expect(await steps('t_s14_live'), 'the run went on to its second step').toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await marks('t_s14_live'), 'the opening of the second step answers the mark of the first, as any opening does').toEqual([false, false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'the approval is in its second step: nothing is left to judge').toBe(0); + }); + + it('[S14] a run with no row on one judgement and back on the next is not placed; one that stays without a row is placed by the judgement after', async () => { + await start('wait_between', 'crm_ticket', 't_s14_norow'); + await decide('t_s14_norow', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_norow'); + const runId = String(first.record_run_id); + await age('t_s14_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // A process that does not hold the run reads no row for it while another advances it. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read no row cannot tell').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + trimmed.delete(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the run is back, parked between two steps').toEqual({ in_progress: 1 }); + + // The row goes again and stays gone: the judgement that reads it + // so starts over, and the one after it places the run. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'read so anew: the earlier reading does not count').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14_norow')).toEqual([false]); + }); + + it('[S14] where the approval holds a decision back, the judgement that first reads a run as stopped past the bound writes nothing, and the next one puts the record back', async () => { + await start('two_step', 'crm_invoice', 'i_s14_held'); + const [first] = await requestsOn('i_s14_held'); + // Decided, marked, and a run that reports paused with no pause; + // no judgement read it before the bound passed. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + await age('i_s14_held'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read it so').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_held'), 'nothing is put back').toBe('pending'); + expect(await marks('i_s14_held')).toEqual([true]); + expect(notified('approval.abandoned'), 'and nobody is told to submit again').toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s14_held')).toBe('recalled'); + expect(await marks('i_s14_held')).toEqual([false]); + }); + + it('[S14] a judgement whose reading cannot be kept leaves nothing for the next to stand on: the approval is held until one is kept, and placed by the judgement after', async () => { + await start('two_step', 'crm_invoice', 'i_s14_unkept'); + await decide('i_s14_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s14_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s14_unkept'); + trimmed.add(String(last.record_run_id)); + await age('i_s14_unkept'); + const update = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + for (const pass of ['the first judgement', 'the one after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}: what it read is not on the request`).toEqual({ undetermined: 1 }); + expect(await keptOn('i_s14_unkept'), pass).toBeUndefined(); + expect(await field('crm_invoice', 'i_s14_unkept'), pass).toBe('pending'); + } + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'the reading is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s14_unkept')).stood, 'with the state it read, and the run').toEqual([`no_row ${String(last.record_run_id)}`]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_unkept')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S14] a batch over records parked on an item that has just ended is not placed by the first judgement that reads it so, and goes on when the engine resumes it', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s14'); + await withoutDoor(() => decide('t_s14', 'approve', 'approver')); + const [first] = await requestsOn('t_s14'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + // The item waits for its own approval longer than the bound. + await age('t_s14'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the item has not ended').toEqual({ in_progress: 1 }); + + // The item's run ends, and the engine has not resumed the batch yet. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the item as ended does not place the batch').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + + // The engine resumes the batch, which goes on to its next item. + await automation.resume(batch); + const next = await itemOf(batch); + expect(next, 'the batch waits on another item').not.toBe(item); + expect(await statusOf(next)).toBe('paused'); + expect(await marks('t_s14'), 'the approval is still held').toEqual([true]); + + // That item ends in turn before a judgement comes. The batch is + // parked on a run that has ended, as the judgement before read + // it; but on another run, so it is read anew. + await automation.cancelRun(next); + expect((await svc.reconcileMarkedApprovals()).judged, 'parked on another item that has ended: not the state read before').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + // Nothing resumes the batch this time, and the judgement after reads the same. + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14')).toEqual([false]); + }); + + it('[S14] a run parked at the step of a request that is still open has not stopped there: what is read while the request is open does not stand once it is decided', async () => { + await start('two_step', 'crm_invoice', 'i_s14_open'); + // The door after the first decision reads the runs with the second request open. + await decide('i_s14_open', 'approve', 'approver'); + const [, open] = await requestsOn('i_s14_open'); + expect([open.status, kept(open)?.stood], 'read with the request open: no state is kept').toEqual(['pending', undefined]); + // The second step is decided, and the process stops before its + // run is resumed and before the door judges. + await withoutDoor(() => settle(withoutResume(() => decide('i_s14_open', 'approve', 'approver2')))); + const [, last] = await requestsOn('i_s14_open'); + expect([last.status, (await automation.suspensionOf(String(last.flow_run_id)))?.nodeId], 'decided, and its run still parked at its step').toEqual(['approved', 'second']); + expect(kept(last)?.stood, 'nothing read while it was open is kept as a state').toBeUndefined(); + await age('i_s14_open'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the run as stopped at its own step').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('pending'); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: placed by its last step').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S14] a state read before a later request opened does not stand for the judgement after it', async () => { + await start('wait_between', 'crm_ticket', 't_s14_later'); + await decide('t_s14_later', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_later'); + const runId = String(first.record_run_id); + // A judgement reads no row for the run, and keeps that on the first request. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ undetermined: 1 }); + expect(kept((await requestsOn('t_s14_later'))[0]).stood).toEqual([`no_row ${runId}`]); + trimmed.delete(runId); + // The run goes on: the second request opens and is decided, with + // no door judging, and the run reaches its end. + await automation.resume(runId); + await withoutDoor(() => decide('t_s14_later', 'approve', 'approver2')); + expect(await statusOf(runId)).toBe('completed'); + expect(await marks('t_s14_later')).toEqual([false, true]); + + // Its row is gone again when the first judgement after comes, past the bound. + trimmed.add(runId); + await age('t_s14_later'); + expect((await svc.reconcileMarkedApprovals()).judged, 'what was read before the second request opened does not stand').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_later')).toEqual([false, true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await marks('t_s14_later')).toEqual([false, false]); + }); + }); + }); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index eb9b812c2de..9cd93c58a77 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -170,7 +170,8 @@ import { } from './payload-redaction.js'; import { APPROVAL_REQUEST_CHILD_OBJECTS, type RequestVisibilitySource } from './request-read-gate.js'; import { - detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval, + ABANDONED_SNAPSHOT_KEY, detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, + recordHeldByLockingApproval, } from './lifecycle-hooks.js'; import { PendingApproverReadGrantSource, type PendingApproverReadGrants } from './pending-approver-read-grant.js'; // The ADR-0043 pages — the ONE copy of their text, rendered by the plugin's @@ -179,6 +180,8 @@ import { APPROVALS_INBOX_PATH, renderConfirmPage, renderResultPage } from './act import { consolePageLink, type ConsolePageComposer } from './public-base-url.js'; import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; +import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; +import { gapsAreAboutTheField, openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, approvalNotificationText, @@ -223,7 +226,18 @@ export interface ApprovalEngine { * registering door wrote for a package, with its `source`. Optional so a * double without it answers "origin unknown", and the gate refuses. */ - registry?: { getPackage?(id: string): { source?: unknown } | undefined }; + registry?: { + getPackage?(id: string): { source?: unknown } | undefined; + /** + * [ADR-0162 Execution item 7] Every registered object, read by the check + * when an approval opens ({@link ApprovalService.judgeOpening}) to learn + * whether any object declares `closedStates`: in an application where + * none does, nothing is read and no approval is refused. Optional: absent, + * the check reads the approval whenever its own record's object declares + * the key. + */ + getAllObjects?(): unknown[]; + }; /** * `ObjectQL.residualOwnerSource`: the registering door's statement for an * artifact residual's owner id, which has no registry row. Read by the same @@ -315,6 +329,17 @@ export interface ApprovalResumeSurface { flowSlotKey?(packageId: string | null, name: string): string | undefined; getFlowSlot?(packageId: string | null, name: string): any | null; getRunFlow?(run: { flowName: string }): any | null; + /** + * [ADR-0162 Execution item 7] The action descriptor a node type publishes + * (ADR-0018), or `undefined` where it publishes none: how the check when an + * approval opens reads whether a node between two steps can pause the run + * of itself (`supportsPause`), following `aliasOf` as the engine's own + * pause gate does. ⚠️ Declares a method `AutomationEngine` ALREADY + * implements publicly (`getActionDescriptor`); it widens no engine surface. + * Optional: absent, every node type but the structural ones counts as one + * that can pause. + */ + getActionDescriptor?(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined; /** * [#35863] A flow name's registrations, oldest first: each body and when it * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell @@ -341,8 +366,41 @@ export interface ApprovalResumeSurface { * therefore acts only on an explicit terminal-failure status and treats * `null` — unknown run, evicted log, no durable store, no automation engine — * as "still alive". - */ - getRun?(runId: string): Promise<{ status?: string; flowName?: string; startedAt?: string } | null>; + * + * [ADR-0162 Execution item 8] Its step log is read too + * (`ExecutionLogEntry.steps`, which the engine already answers): the door + * that judges an approval places where the run stopped, and a failure the + * flow routed, against the set the approval's requests carry. A step inside + * a region names its container (`parentNodeId`). A delegating step names + * the child runs it started (`childRunIds`), which the door reads in turn, + * and a run names the record it carries (`trigger`). The door reads with + * `strict`: a store that does not answer throws, so that it is not taken + * for a run with no row (an engine that does not know the option reads as + * before). + */ + getRun?(runId: string, options?: { strict?: boolean }): Promise<{ + status?: string; + flowName?: string; + startedAt?: string; + completedAt?: string; + trigger?: { object?: string; recordId?: string }; + steps?: ReadonlyArray<{ + nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string; + childRunIds?: readonly string[]; + /** + * [seat ruling 7258590209 on #37767] The engine names at most 200 child + * runs on a step, and sets this where the step's execution started + * more. The door reads such a step as cannot tell ({@link stepLogCut}). + */ + childRunIdsTruncated?: boolean; + }>; + /** + * The run's summary (`ExecutionLog.summary`), folded from every step the + * run logged before its history row bounds the step log: how the door + * tells a step log its row cut short ({@link stepLogCut}). + */ + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps * a decision from being recorded against a run that can never advance @@ -1783,6 +1841,623 @@ function parseJson(raw: unknown, fallback: T): T { /** [#24577] What {@link ApprovalService.mirroredStatusValue} answers when a transition writes nothing. */ const STATUS_NOT_MIRRORED = Symbol('status-not-mirrored'); +/** + * [ADR-0162 D5] The statuses the mirror writes for a request of an approval: + * a closed value outside these was not written by the approval. + */ +const MIRRORED_REQUEST_STATUSES: ReadonlySet = new Set(['pending', 'returned', 'approved', 'rejected']); + +/** + * [ADR-0162 Execution item 8] The request a write of the status mirror is + * about, so that a refusal on a field the object closes on can be told on that + * request (`ApprovalService.reportRefusedMirror`). `opening` is set by the one + * caller that answers the refusal itself: the `pending` of an approval's first + * request, whose refusal refuses the opening. + */ +interface MirrorRequestRef { + readonly request: any; + readonly step?: string | null; + readonly opening?: boolean; +} + +/** A write of the status mirror refused on a field the object closes on. */ +interface MirrorRefusal { + readonly refused: unknown; + readonly message: string; +} + +/** + * [ADR-0162 Execution item 8] The topic of the notice the organization's + * administrators get when a rule or a hook of the app refuses a write of the + * status mirror on a field the object closes on. + */ +const REFUSED_MIRROR_TOPIC = 'approval.status_mirror_refused'; + +/** + * [ADR-0162 D5, Execution item 8] The topic of the notice the submitter gets + * when the approval of their record ended between two of its steps and the + * plugin put the record back. + */ +const ABANDONED_APPROVAL_TOPIC = 'approval.abandoned'; + +/** + * [ADR-0162 Execution item 8, ruling B2 on #37767] The topic of the notice + * the organization's administrators get when an approval was decided at its + * last step and its outcome written, while its flow could not be seen through + * to its end after that step: it did not go on, or the plugin could not read + * all of it. + */ +const FLOW_NOT_CONTINUED_TOPIC = 'approval.flow_not_continued'; + +/** + * [ADR-0162 Execution item 8] The keys of a request's config snapshot that the + * judgement of an approval leaves: the approval was abandoned (`__abandoned`), + * and a later step of it could not open (`__laterStepNotOpened`). Internal + * stamps, like `__round`: the snapshot is not authored config. The first is + * read by the hold as well (`lifecycle-hooks.ts`), which owns its spelling. + */ +const ABANDONED_KEY = ABANDONED_SNAPSHOT_KEY; +const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; + +/** The run statuses a run reports while it is being advanced, or is about to be. */ +const ADVANCING_RUN_STATUSES: ReadonlySet = new Set(['pending', 'running', 'retrying']); + +/** + * [ADR-0162 Execution item 8] The terminal statuses of a run that reached an + * `end` the flow declares: `completed`, and `refused` (an `end` with + * `outcome: 'refused'`, a successful evaluation that said no). Such a run + * stopped nowhere between two steps, so the door reads it as finished, a + * failure it routed on the way apart. An `end` logs no step of its own, so + * the last step of a refused run is the node before it, often the approval + * that was just decided, and must not be read as where the run stopped. + */ +const REACHED_AN_END: ReadonlySet = new Set(['completed', 'refused']); + +/** + * [ADR-0162 Execution item 8] Where a terminal run stopped, read off its step + * log: the last step at the top level of the run (one that ran in no + * `loop`, `parallel` or `try_catch` region), else the last step. An + * unrouted failure is the last step a run logs, and a run that was cancelled, + * failed by a child's failure or settled as unresumable logs nothing after + * the node it stood on, so the last step names that node; an earlier failure + * that the flow routed on is not where the run stopped. Two failures log no + * step for the node the run died on: the engine's re-entry guard, and a + * suspension refused inside a region. There the last step logged is the node + * before it, and the run is placed by that node. `undefined` for a run that + * reached an `end` ({@link REACHED_AN_END}). + */ +function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }>, status: string): string | undefined { + if (REACHED_AN_END.has(status)) return undefined; + const last = [...log].reverse().find((s) => !s?.parentNodeId) ?? log[log.length - 1]; + return last && typeof last.nodeId === 'string' ? last.nodeId : undefined; +} + +/** [ADR-0162 Execution item 8] One step of a run's log, as the door reads it. */ +type RunStepRead = { + nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; childRunIds?: unknown; + childRunIdsTruncated?: unknown; +}; + +/** + * [ADR-0162 Execution item 8] How many runs one judgement of an approval + * reads, at most, beside those it kept as ended and does not read again. It + * is also how many runs each list of the kept reading holds + * ({@link RunsRead}). + * + * A tree of more runs is read over several judgements, each reading on from + * what the approval kept. Within the age bound such a judgement answers that + * it cannot tell, and the approval keeps its mark. Past the bound it answers + * so only while it keeps a run the approval had not kept; the judgement that + * keeps none cannot finish the tree, and the approval is placed by the step + * last decided, as a tree the judgement before it met too + * ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review 7266979193). The + * kept list only grows and holds this many runs, so the judgements that + * read on are numbered: at most this many passes of the reconciler. + * + * The tree it does not finish is placed without being finished, which is + * the cost the seat accepted with that rule (L1 7269166540). It is not only + * a tree of more runs than the two kept lists hold: the walk reads the runs + * it starts from before the runs below them, so a `map` of 199 items that + * each call a `subflow`, about 399 runs, is already one no reading finishes + * (N26 of delta review 7269135624). And the placement follows from the + * flow's shape, so an approval submitted again on the same flow meets the + * same end (N27 of that review). + * + * It is also how many child runs the engine names on one step before it + * marks the step (`childRunIdsTruncated`); the suite ties the two on a real + * run (N21 of that review), for which it is exported from this module. + */ +export const MAX_RUNS_READ_PER_APPROVAL = 200; + +/** + * [ADR-0162 Execution item 8] How long an approval's marks stand before the + * reconciler reads a run in one of six states as stopped. It is measured + * from the marks: every mark of the approval has stood this long. Within it + * nothing is written for any of the six states it governs, at the + * approval's last step as at any other (ruling 3 on #37767). + * + * Past it, a state says the run has stopped only where two judgements in a + * row read it, for the same run (S14 of delta review 7269135624; + * {@link stoodState}). The hour is counted from the marks and not from the + * run's last movement, so an approval that waits longer than the hour + * between two steps by design (a `wait` node, a batch over records whose + * items are approved one by one, a child parked outside the set) is past + * the bound from the first instant of every later resume; and a run the + * engine is resuming reads as paused with its pause gone, or as a run with + * no row. Only an approval that holds nothing back can wait so: the check + * at its opening refuses each of the three between two steps of an approval + * whose object closes on the step's field (ADR-0162 D5, condition 5), so a + * placement inside such a passage ends a hold early and writes nothing + * (N31 of delta review 7270552441). That state clears within the passage, + * and the one a dead process left is read again by the next judgement. The + * judgement that reads a state for the first time answers that it cannot + * tell, and keeps what it read; a judgement within the bound keeps it too, + * so an approval that was read within the hour is placed by the first + * judgement past it. The six: + * + * - a run that reports paused while its pause is gone has stopped at the + * last step it logged; + * - a run parked at a `subflow` or a `map` whose child run has ended, has + * no row, or will not go on itself, has stopped at that node. An item + * run of a `map` that carries another record is such a child once it is + * in a terminal status (S12 of contract review 7266979193); + * - a run with no row that no run the plugin read speaks for, + * - a run whose step log does not name every child run it started + * ({@link stepLogCut}; seat ruling 7258590209), + * - a tree of more runs than one judgement reads, once a judgement keeps + * no run the approval had not kept ({@link MAX_RUNS_READ_PER_APPROVAL}; + * S11 of that review: the runs it does not get to are runs the plugin + * never read, and the cost is the one ruling 7258590209 accepted for a + * truncated step), and + * - the latest request's own run still parked at the step its decision was + * recorded on, have each stopped at the step last decided (rulings A3 and + * B2 on #37767, one rule). + * + * One hour: far past any passage a live process completes (a passage is the + * work between a decision and the next step, run in the same call), and + * short enough that a record a dead process left held is released the same + * working session. A passage that begins after the hour is what the second + * reading is for. Two judgements in a row that each fall inside a passage + * of the same run, one passage or two, still read it as stopped: the sweep + * clock sets how far apart two passes of one process are, and nothing sets + * it for two processes or for a pass at boot. + */ +export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; + +/** + * How many steps the engine keeps of a terminal run's log before the history + * row bounds it by bytes (its `MAX_PERSISTED_HISTORY_STEPS`). Only read by + * {@link stepLogCut}: were the engine to keep fewer, more logs would read as + * cut, which is the safe side. Were it to keep more, a row cut to a length + * between the two numbers would compare as whole, so the suite pins this + * number to the engine's (N21 of contract review 7266979193), for which it + * is exported from this module. + */ +export const HISTORY_STEPS_KEPT = 200; + +/** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on M5 of review record + * 7258563513] Why a run's step log does not name every child run its steps + * started, or `undefined` where it does. Such a log cannot be judged from: + * the runs it leaves out are not read, and it does not speak for the runs + * it does name. + * + * - A step carries `childRunIdsTruncated`: its links to child runs were + * shed. Its execution started more child runs than the 200 the engine + * names on a step, or the history row shed the step's list to fit its + * size. + * - The history row of a run in a terminal status keeps fewer steps than + * the run logged. The row bounds the log by bytes: over the bound it + * keeps a tail of it, or stores none. The run's summary is folded before + * that, and counts one execution or one skip for every step logged, so + * the two are compared. A log of more steps than the engine keeps + * ({@link HISTORY_STEPS_KEPT}) is compared with that number: the engine's + * own compaction of a long log is not a cut of the row. A summary that + * is absent, or that dropped its per-node detail, gives nothing to + * compare, and the log is read as cut. + * + * [Ruling 7268216330 on #37767, its question q1: as built] The mark is the + * only one the engine leaves. A log that loses whole steps carries none: + * the engine's compaction of a log of more than {@link HISTORY_STEPS_KEPT} + * steps, the row's halving over its size cap, a row stored as null. The + * plugin reads what the log kept. The second case above tells a halved row + * and a null row from the summary; a compacted log gives nothing to tell it + * by, and a child run named only by a step the compaction dropped reads as + * one the run went past. That is a stated limit of this release. + * + * A run that has not ended is read from its pause, whose step log is not + * bounded, so only the mark applies to it. + */ +function stepLogCut( + run: { summary?: { nodes?: ReadonlyArray<{ runs?: unknown; skipped?: unknown }>; detailOmitted?: unknown } | null }, + steps: readonly RunStepRead[], + terminal: boolean, +): string | undefined { + const marked = steps.find((s) => s?.childRunIdsTruncated === true); + if (marked) return `its step '${String(marked.nodeId)}' started more child runs than it names`; + if (!terminal) return undefined; + const nodes = run.summary?.detailOmitted ? undefined : run.summary?.nodes; + if (!Array.isArray(nodes)) return 'its summary does not say how many steps it logged'; + let logged = 0; + for (const n of nodes) logged += (Number(n?.runs) || 0) + (Number(n?.skipped) || 0); + return steps.length < Math.min(logged, HISTORY_STEPS_KEPT) + ? `its history keeps ${steps.length} of the ${logged} steps it logged` + : undefined; +} + +/** + * [ADR-0162 Execution item 8] A child run a step names, whether a `map` step + * started it, and whether the run that names it went on past that step + * (`passed`, {@link childRunsOf}). + */ +interface ChildRunRef { + readonly id: string; + readonly item: boolean; + readonly passed: boolean; +} + +/** + * [ADR-0162 Execution item 8] The child runs a run's steps name + * (`childRunIds`), to read next: every child of a `subflow` step, and every + * item run of a `map` step, which the walk reads to tell whether it carries + * another record (an item that is a record carries an approval of its own). + * + * `passed` (the seat's reading 7257555103 of ruling A3): the run went on + * past the step that names the child. The step succeeded, and the run + * reached an end of its flow (`reachedAnEnd`) or logged a later step. The + * engine logs one step for each visit of a node, a visit that paused and + * was resumed included, and a run stands at the last step it logged (as + * {@link stopOf} reads it), so a later step says the visit is over and + * every child of it has ended. Two things are never passed: + * + * - the latest visit of the node a paused run is parked at (`parkedAt`), + * whatever was logged after it: a step on another branch of the flow can + * be logged after the visit that parked the run; + * - a step that failed, also where the flow routed its failure and went on + * (the maintainer's pin on that reading): what such a run did after the + * step says nothing of the child. + * + * And a log that is cut ({@link stepLogCut}, `speaks` false) passes none: + * it does not speak for the runs it names. + */ +function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string, speaks = true): ChildRunRef[] { + const out: ChildRunRef[] = []; + const parkedVisit = parkedAt === undefined ? -1 : steps.map((s) => s?.nodeId).lastIndexOf(parkedAt); + steps.forEach((s, i) => { + if (!Array.isArray(s?.childRunIds)) return; + const passed = speaks && s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1); + for (const id of s.childRunIds) { + if (typeof id !== 'string' || !id) continue; + out.push({ id, item: s.nodeType === 'map', passed }); + } + }); + return out; +} + +/** [ADR-0162 Execution item 8] The child run a parked `subflow` or `map` waits on, from its correlation. */ +function childOfCorrelation(correlation: string): string | undefined { + for (const prefix of ['subflow:', 'map:']) { + if (correlation.startsWith(prefix)) return correlation.slice(prefix.length) || undefined; + } + return undefined; +} + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] The key of a request's + * config snapshot that keeps what the plugin read of its approval's runs, at + * each door and as each request opens, so that a later judgement does not + * depend on run histories the automation engine is free to trim. + */ +const RUNS_READ_KEY = '__runsRead'; + +/** How many times {@link ApprovalService.keepRunsRead} tries its conditional write. */ +const KEEP_RUNS_READ_ATTEMPTS = 3; + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What the plugin kept of + * an approval's runs, in the thin form: + * + * - `ended`: the runs a later judgement does not read again. A run enters + * it only once it was read to an end and every child run its steps name + * is in it too ({@link keptAsEnded}), so a run kept here never hides a + * run that was not read. An end is a terminal status, also for an item + * run of a `map` that carries another record, whose steps are not read; + * and a run with no row that a run the plugin read went on past + * ({@link childRunsOf}); + * - `open`: the runs read in a terminal status that are not in `ended` + * yet, because a child they name was not read to such an end. The next + * judgement starts from them as well, so they are read again while their + * row lasts; and one whose row is gone by then is not taken as passed, + * since nothing can name its children any more; + * - `between`: a failure between two steps found in a run that ended, with + * its instant, which counts while no later request of the approval + * opened after it (an instant it could not read always counts); + * - `stood`: the states the last judgement read that say a run has stopped + * only once they stand ({@link stoodState}), each with its run. It is + * what that one judgement read and no more: the next judgement places a + * run only where its state is in this list, and writes its own list in + * its place (S14 of delta review 7269135624). It holds at most two + * states for each run one judgement reads, and one for the tree. + * + * A run that has not ended is not kept: the engine does not trim it, and + * the walk reaches it again from the runs above it. + */ +interface RunsRead { + readonly ended: readonly string[]; + readonly open: readonly string[]; + readonly between?: { readonly why: string; readonly at: string | null }; + readonly stood?: readonly string[]; +} + +/** + * [ADR-0162 Execution item 8, S14 of delta review 7269135624] A state of a + * run that says the run has stopped only once it stands: a judgement past + * the age bound places it only where the judgement before read the same + * state for the same run ({@link RunsRead}, `stood`). While the engine + * advances a run, the run has no pause and has not parked again or ended, + * so every reader sees it as paused with its pause gone, or as a run with + * no row; and between a child's end and the resume of the run parked on it, + * that run is parked on a child that has ended. Each of these is also what + * a dead process leaves. The first clears within the passage that causes + * it, and the second stands. + * + * - `pause_gone`: the run reports paused, and no pause of it can be found; + * - `on_ended`: the run is parked at a `subflow` or a `map` on the child + * `on`, which has ended or has no row; + * - `own_node`: the latest request's own run is still parked at the step + * its decision was recorded on; + * - `cut`: the run's step log does not name every child run it started; + * - `no_row`: the run has no row, and no run that was read speaks for it; + * - `tree`: the approval's runs number more than one judgement reads (on + * the run that carries the record). + * + * Spelled with spaces, kind first: it is compared as a whole and never + * parsed, and it is not of the `:` shape this package keeps for + * approver addresses. + */ +function stoodState(kind: 'pause_gone' | 'on_ended' | 'own_node' | 'cut' | 'no_row' | 'tree', runId: string, on?: string): string { + return on === undefined ? `${kind} ${runId}` : `${kind} ${runId} ${on}`; +} + +/** The instant of an ISO date, or `NaN`. */ +function instantOf(v: unknown): number { + return v == null || v === '' ? NaN : new Date(v as string).getTime(); +} + +/** + * [ruling A3] What the requests of one approval kept of its runs, merged + * ({@link RUNS_READ_KEY}); `approval` is read oldest first. `stood` is not + * merged: it is the list on the approval's latest request, where every + * judgement keeps its reading, and no other. A request that opened since + * the last judgement carries none, so the states are read anew after it. + */ +function runsReadOf(approval: readonly any[]): RunsRead { + const ended = new Set(); + const open = new Set(); + let between: RunsRead['between']; + let stood: string[] = []; + const latest = approval[approval.length - 1]; + for (const r of approval) { + const kept = parseJson>(r?.node_config_json, {})[RUNS_READ_KEY] as Partial | undefined; + if (!kept || typeof kept !== 'object') continue; + if (r === latest && Array.isArray(kept.stood)) stood = kept.stood.filter((v): v is string => typeof v === 'string' && v !== ''); + for (const id of Array.isArray(kept.ended) ? kept.ended : []) if (typeof id === 'string' && id) ended.add(id); + for (const id of Array.isArray(kept.open) ? kept.open : []) if (typeof id === 'string' && id) open.add(id); + const b = kept.between; + if (b && typeof b === 'object' && typeof b.why === 'string') { + const at = typeof b.at === 'string' ? b.at : null; + // The latest kept failure: the one a later opening is least likely to have answered. + if (!between || !(instantOf(at) <= instantOf(between.at))) between = { why: b.why, at }; + } + } + // A run one request kept as open and a later one as ended has ended. + return { + ended: [...ended], open: [...open].filter((id) => !ended.has(id)), ...(between ? { between } : {}), + ...(stood.length > 0 ? { stood } : {}), + }; +} + +/** Whether two kept readings say the same, whatever the order of their lists. */ +function sameRunsRead(a: RunsRead, b: RunsRead): boolean { + const same = (x: readonly string[], y: readonly string[]) => x.length === y.length && [...x].sort().join('\n') === [...y].sort().join('\n'); + return same(a.ended, b.ended) && same(a.open, b.open) && same(a.stood ?? [], b.stood ?? []) + && JSON.stringify(a.between ?? null) === JSON.stringify(b.between ?? null); +} + +/** + * [ADR-0162 Execution item 8, M4 of contract review 7257527251] Of the runs + * one reading found at an end (`over`), those it may keep as ended. A run + * kept as ended is not read again, and so the child runs its steps name are + * never reached through it again: it is kept only where every child it + * names is kept as ended too, in this reading or an earlier one + * (`settled`). A child whose read threw, a child the reading did not get to + * (the cap), a child that has not ended and a child with no row that no run + * went on past each leave the runs above them to be read again. + */ +function keptAsEnded( + over: ReadonlySet, + childrenOf: ReadonlyMap, + settled: ReadonlySet, +): Set { + const keep = new Set(over); + for (let changed = true; changed;) { + changed = false; + for (const id of keep) { + const children = childrenOf.get(id); + if (!children || children.some((c) => !keep.has(c) && !settled.has(c))) { + keep.delete(id); + changed = true; + } + } + } + return keep; +} + +/** + * [ADR-0162 Execution item 8] What one reading of an approval's runs found, + * for {@link runsReadAfter}: the runs read in a terminal status + * (`terminal`), the item runs of another record that are in a terminal + * status (`foreign`), the runs with no row (`noRow`), the runs a run that + * was read went on past (`passed`), the child runs each run that was read + * names (`childrenOf`), and the states it read that say a run has stopped + * only once they stand (`stood`, {@link stoodState}). + */ +interface RunsFound { + readonly terminal: Set; + readonly foreign: Set; + readonly noRow: Set; + readonly passed: Set; + readonly childrenOf: Map; + readonly stood: Set; +} + +const noRunsFound = (): RunsFound => ({ + terminal: new Set(), foreign: new Set(), noRow: new Set(), passed: new Set(), childrenOf: new Map(), stood: new Set(), +}); + +/** + * [the seat's reading 7257555103 of ruling A3] The runs with no row that a + * run the plugin read speaks for: it went on past the step that names them, + * so they count as passed at that step. Not one the plugin kept as `open`: + * it read that run to its end over a child it could not read, and a row + * that is gone no longer names that child. + */ +function passedWithNoRow(prior: RunsRead, found: RunsFound): Set { + const open = new Set(prior.open); + return new Set([...found.noRow].filter((id) => found.passed.has(id) && !open.has(id))); +} + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] The kept reading after + * one more reading: what was kept before (`prior`) with what this one found. + * `ended` only grows, by the runs {@link keptAsEnded} allows; `open` is the + * runs read in a terminal status, now or before, that are not ended. + * + * Each of the two lists holds at most {@link MAX_RUNS_READ_PER_APPROVAL} + * runs. A run left out of `ended` is read again, which costs a read and + * changes no answer. + * + * A reading whose `open` would not fit keeps both lists as they were (N25 + * of delta review 7269135624: this is what the rule does). The runs it read + * in a terminal status beyond them are then in neither list: they are not + * kept as open, so one of them whose row is gone by a later reading can be + * taken as passed where a run that was read went on past it + * ({@link passedWithNoRow}). The rule does not prevent that. It does not + * change the answer either, by two facts nothing pins: a list holds as many + * runs as one judgement reads, and the walk reads the runs it starts from, + * the `open` runs among them, before the runs below them (the child a + * parked run waits on excepted). So `open` passes the bound only where the + * approval already holds nearly that many open runs, and from then on every + * reading spends its reads on them and cannot finish the tree: the approval + * is cannot tell and, past the age bound, placed. + * + * `stood` is not merged: it is what this reading read ({@link RunsRead}). + */ +function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['between']): RunsRead { + const settled = new Set(prior.ended); + const gone = passedWithNoRow(prior, found); + const childrenOf = new Map(found.childrenOf); + for (const id of [...found.foreign, ...gone]) childrenOf.set(id, []); + const now = keptAsEnded(new Set([...found.terminal, ...found.foreign, ...gone]), childrenOf, settled); + const open = [...new Set([...prior.open, ...found.terminal])].filter((id) => !settled.has(id) && !now.has(id)); + const rest = { ...(between ? { between } : {}), ...(found.stood.size > 0 ? { stood: [...found.stood] } : {}) }; + if (open.length > MAX_RUNS_READ_PER_APPROVAL) return { ended: prior.ended, open: prior.open, ...rest }; + const ended = [...prior.ended, ...[...now].filter((id) => !settled.has(id))].slice(0, MAX_RUNS_READ_PER_APPROVAL); + return { ended, open, ...rest }; +} + +/** + * [ADR-0162 Execution item 8] What one run of an approval's tree answered + * when the door read it (`ApprovalService.readApprovalRun`): + * + * - `undetermined`: it cannot be read or placed now; + * - `no_row`: the engine holds no row for it; + * - `foreign`: an item run of a `map` that carries another record. Its + * steps are an approval of that record and are not read; `over`: it is + * in a terminal status, so the batch parked on it has nothing left to + * wait for; + * - `in_progress`: parked at a node of the set, on nothing the walk reads; + * - `waits`: parked at a node of the set (`node`) on a child run (`on`), + * which says what this run says (`ApprovalService.waitingRun`); + * - `own_node`: the latest request's own run, parked at that request's node; + * - `read`: everything else. `over`: it is in a terminal status. `stopped`: + * it reports paused at a pause that is gone, past the age bound and as + * the judgement before read it ({@link stoodState}), so it will not go + * on. `endedWhy`: it ended, or stopped, between two steps. + * + * `cut`, on any of the last four: why its step log does not name every + * child run it started ({@link stepLogCut}). + */ +type ApprovalRunRead = + | { answer: 'undetermined'; why: string } + | { answer: 'no_row' } + | { answer: 'foreign'; over: boolean } + | { answer: 'in_progress'; children: ChildRunRef[]; cut?: string } + | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[]; cut?: string } + | { answer: 'own_node'; flow?: string; children: ChildRunRef[]; cut?: string } + | { answer: 'read'; over: boolean; stopped?: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[]; cut?: string }; + +/** + * [ADR-0162 Execution item 8] What the door answered for an approval after it + * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). + * `unstamped`: the approval was not stamped, and nothing is judged. `judged`: + * no request of it carries the mark, or a writer that recalled its latest + * request already wrote what it leaves. `ended`: it ended between two steps + * and held nothing back, so only the mark was cleared. + */ +type ApprovalJudgement = 'unstamped' | 'judged' | 'in_progress' | 'undetermined' | 'finished' | 'abandoned' | 'ended'; + +/** One node of the between-two-steps set a request carries (`between_steps_json`). */ +interface StampedNode { + readonly flow: string; + readonly node: string; +} + +/** + * [ADR-0162 Execution item 8] The between-two-steps set `row` carries, or + * `undefined` where its approval was not stamped: no step of it can act on an + * object that declares `closedStates`, or the plugin could not place it. An + * empty set (`[]`) is a stamp: such an approval is judged like any other. + */ +function stampOf(row: any): StampedNode[] | undefined { + const raw = row?.between_steps_json; + if (typeof raw !== 'string' || raw === '') return undefined; + const parsed = parseJson(raw, undefined); + if (!Array.isArray(parsed)) return undefined; + return parsed + .filter((n): n is { flow?: unknown; node?: unknown } => !!n && typeof n === 'object') + .map((n) => ({ flow: String(n.flow ?? ''), node: String(n.node ?? '') })) + .filter((n) => n.node !== ''); +} + +/** + * [ADR-0162 Execution item 8] Whether the node `nodeId` of the flow `flow` + * stands in `stamp`. The set names each flow by the key the engine files it + * under; where the run's own flow key is unknown, or names no flow of the set, + * the node is matched by its id alone, which can only read more stops as + * between two steps (a resubmission), never fewer (a closed document on an + * unfinished approval). + */ +function standsBetweenSteps(stamp: readonly StampedNode[], flow: string | undefined, nodeId: string): boolean { + if (flow && stamp.some((n) => n.flow === flow)) return stamp.some((n) => n.flow === flow && n.node === nodeId); + return stamp.some((n) => n.node === nodeId); +} + +/** [ADR-0162 Execution item 8] Whether `row` carries the mark: it was decided, and what follows is not judged yet. */ +function isMarked(row: any): boolean { + return row?.unjudged_since != null && row.unjudged_since !== ''; +} + +/** The timeline line an approval that ended between two steps leaves on its latest request. */ +function abandonedNoteText(why: string, left: string): string { + return `The approval did not go on: ${why} ${left}`; +} + +/** The timeline line a refused write of the status mirror leaves on its request. */ +function refusedMirrorNoteText(status: string, reason: string): string { + return `The approval status '${status}' could not be written to the record: ${reason}`; +} + /** * [#24577] The values a status field declares, read as the engine's record * validator reads a select's options (objectql `record-validator.ts`, @@ -2356,6 +3031,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * walk again, which costs a repeat, never a miss. */ private strandScanCursor: string | null = null; + /** [ADR-0162 Execution item 8] Where the reconciler's walk over the marked requests stopped ({@link reconcileMarkedApprovals}). */ + private reconcileScanCursor: string | null = null; private readonly getConsoleUrl?: ConsolePageComposer; private tenancyPosture?: () => string | undefined; private fieldVisibility?: FieldVisibilitySource; @@ -2624,6 +3301,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.automation = automation; } + /** + * [ADR-0162 D5, Execution item 7] Whether the host runs this plugin's sweeps: + * the plugin calls {@link noteSweepClockScheduled} once it has scheduled them + * on the host's `job` service. The sweeps are what ends an approval nobody + * is at the door for (ADR-0162 item 8, the reconciler), so on a host with no + * `job` service the first request of every approval a step of which can act + * on an object that declares `closedStates` is refused, saying what is + * missing (seat rulings 7211509661 and 7211531658, the seat's ruling on the + * design note 7210179412). `false` until noted. + */ + private sweepClockScheduled = false; + + /** [ADR-0162 Execution item 7] The plugin scheduled its sweeps on the host's `job` service ({@link sweepClockScheduled}). */ + noteSweepClockScheduled(): void { + this.sweepClockScheduled = true; + } + /** Attach (or replace) the messaging surface used for thread notifications. */ attachMessaging(messaging: ApprovalMessagingSurface): void { this.messaging = messaging; @@ -4985,6 +5679,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * **The value written is one the field declares (#24577).** What is written * is {@link mirroredStatusValue}'s answer, and `abandoned` (the request's * row, on a transition that abandons it) is what that answer may restore. + * + * **An abandoned request never writes a closed value (ADR-0162 D5, ruling + * record 7201405662).** On a transition that abandons a request, where the + * object's `closedStates` lists any value for `field`, the value is + * {@link abandonedValueOnClosingField}'s answer instead, and that answer may + * be to write nothing. Every other write, and every write on an object that + * closes on no value of `field`, is chosen as above. + * + * **A refused write on a field the object closes on is not swallowed + * (ADR-0162 D5, Execution item 8).** A validation rule, an option's + * `visibleWhen` or a hook of the app can refuse this write, and no reading of + * a definition shows when. Where the object closes on `field` at `approved` or + * `rejected` ({@link closesOnApprovalOutcome}) and `about` names the request, + * the refusal is answered as `{ refused }` and, unless `about.opening` says the + * caller refuses the opening itself, reported by + * {@link reportRefusedMirror}. On every other field the write keeps its + * best-effort `warn`, as before. */ private async mirrorStatusField( object: string, @@ -4994,116 +5705,1874 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega actorId: string | null, requestOrg: string | null | undefined, abandoned?: { payloadJson: unknown }, - ): Promise { + about?: MirrorRequestRef, + ): Promise { try { - const value = this.mirroredStatusValue(object, field, status, abandoned); + // [ADR-0162 D5, Execution item 7] An abandoned request on a field the + // object closes on, on any value of it: no closed value is written, and + // a closed value the approval did not write is left alone. + const closed = abandoned ? this.closedValuesOf(object, field) : []; + let value: unknown; + if (abandoned && closed.length > 0) { + const choice = await this.abandonedValueOnClosingField(object, recordId, field, closed, abandoned, about); + if ('leave' in choice) return undefined; + value = choice.write; + } else { + value = this.mirroredStatusValue(object, field, status, abandoned); + } if (value === STATUS_NOT_MIRRORED) { this.logger?.warn?.( `[approvals] approval status '${status}' was not written to ${object}.${field}: the field's options do not ` + `declare it, so the field keeps its value. Declare '${status}' among the field's options to mirror this transition.`, { object, record: recordId, field, value: status }, ); - return; + return undefined; } const context = actorId ? await this.attributedMirrorContext(object, recordId, actorId, requestOrg) : SYSTEM_CTX; await this.engine.update(object, { id: recordId, [field]: value }, { context }); + return undefined; } catch (err: any) { + if (about && this.closesOnApprovalOutcome(object, field)) { + const refusal: MirrorRefusal = { refused: err, message: String(err?.message ?? err) }; + if (!about.opening) { + await this.reportRefusedMirror(object, recordId, field, status, refusal.message, about, requestOrg); + } + return refusal; + } this.logger?.warn?.(`[approvals] mirrorStatusField failed: ${err?.message ?? err}`); + return undefined; } } /** - * [#24577] The value a status mirror writes onto `object.field` for - * `status`, or {@link STATUS_NOT_MIRRORED} when it writes nothing. - * - * A field's declared options are its value set (the triage ruling on the - * card): the producer never writes outside them. The engine's validator does - * not hold that line for this write — it judges a `readonly` field's value - * for shape only, and the mirrored field is readonly by the spec's own advice - * — so a select that never declared `recalled` came to hold it, and an app - * whose submit gate admits only the select's own values never re-entered - * approval. The options are read from the registry the engine validates the - * same write against (`getSchema` answers `registry.getObject`). - * - * - A field with no declared value set ({@link declaredOptionValues}) and a - * status the field declares: the status, as before. - * - A transition that ABANDONS the request (a recall, the dead-run sweep), - * `abandoned` set: the record goes back to where it stood before it - * entered approval. That is the value the field held in the request's - * submit snapshot (`payload_json`, the trigger record the flow started - * from) when that is a declared value or none; else what a never-submitted - * record carries — the field's declared default, or empty. Whether the - * record re-enters approval is then the app's own gate's decision. - * - Every other transition (open, decide, send-back, the revision-limit - * auto-reject): nothing. Send-back is here, not with recall, because its - * run is still alive in the revise window (ADR-0044): a pre-approval value - * restored there re-admits the start condition ADR-0044 tells authors to - * gate on this field, and opens a parallel approval of the same record. + * [ADR-0162 D5] Whether `object` closes on `field` at an approval's outcome: + * its `closedStates` lists `approved` or `rejected` for that field. Read from + * the registry the engine validates the mirror's write against, as + * {@link mirroredStatusValue} reads the field's options. An object that + * declares no closed state answers `false`, and its mirror behaves as it did + * before the key. */ - private mirroredStatusValue( - object: string, - field: string, - status: string, - abandoned: { payloadJson: unknown } | undefined, - ): unknown { - let def: { defaultValue?: unknown } | undefined; + private closesOnApprovalOutcome(object: string, field: string): boolean { + let closedStates: unknown; try { - const schema = this.engine.getSchema?.(object) as { fields?: Record } | undefined; - def = schema?.fields?.[field] as typeof def; - } catch { /* schema unavailable — no declared value set to hold the write to */ } - const declared = declaredOptionValues(def); - if (!declared || declared.includes(status)) return status; - if (!abandoned) return STATUS_NOT_MIRRORED; - const snapshot = parseJson(abandoned.payloadJson, undefined); - if (snapshot && typeof snapshot === 'object' && Object.prototype.hasOwnProperty.call(snapshot, field)) { - const held = (snapshot as Record)[field]; - if (held == null) return null; - if (holdsDeclaredValues(held, declared)) return held; - } - return holdsDeclaredValues(def?.defaultValue, declared) ? def!.defaultValue : null; - } - - /** - * The context a named actor's status mirror writes under (see - * {@link mirrorStatusField}): `{ isSystem: true, userId, tenantId }` and - * nothing else. The organisation is the subject record's live one, read - * through {@link recordOrgResolver} — the resolver the request row was - * stamped by — and the request's own organisation for an object that has - * none (or a record that carries none), as at the stamp. ⛔ No `positions` / - * `permissions`: a carried array is kept verbatim by every `runAs:'user'` - * consumer, so an empty one would stand in for the actor's own grants. - */ - private async attributedMirrorContext( - object: string, - recordId: string, - actorId: string, - requestOrg: string | null | undefined, - ): Promise { - const column = this.recordOrgResolver.organizationFieldFor(object); - let organization: string | null = null; - if (column) { - const rows = await this.engine.find(object, { - where: { id: recordId }, fields: ['id', column], limit: 1, context: SYSTEM_CTX, + closedStates = (this.engine.getSchema?.(object) as { closedStates?: unknown } | undefined)?.closedStates; + } catch { /* schema unavailable — no closed state can be read, as for the value set above */ } + if (!closedStates || typeof closedStates !== 'object') return false; + const closed = (closedStates as Record)[field]; + return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); + } + + /** + * [ADR-0162 D5, Execution item 8] Whether a decision on `row`'s step is held + * back: `row` is a request of an approval the check stamped when it opened, + * and its object closes on `field` at `approved` or `rejected`. Both + * decisions are held back, whichever of the two the object closes on, and + * the field keeps `pending` until the approval is over + * ({@link judgeApprovalAfterDoor}). Every other status is written as before. + */ + private holdsBackDecision(row: any, field: string): boolean { + return stampOf(row) !== undefined && this.closesOnApprovalOutcome(String(row?.object_name ?? ''), field); + } + + /** + * [ADR-0162 D5, Execution item 8] The door's judgement of an approval, after + * a door resumed or cancelled one of its runs: a decision (by a person or + * the platform's clock), a send-back, a resubmission, a recall and the + * continuation of a restored run. It never takes the resume's own answer + * for it, which is about the request's own run. + * + * The approval is the request's root run, on the request's record. The door + * asks its own table for the approval's requests on the record and reads + * every run of the approval, from the run that carries the record + * (`record_run_id`) down the child runs its steps name, beside what the + * approval kept of runs it read before ({@link readCarryingRun}; what this + * reading showed is kept in turn, {@link keepRunsRead}). It reads and keeps + * at every door, also at one that leaves a request open, whose answer it + * does not need (the seat's reading 7257555103 of ruling A3). It answers + * one of: + * + * - **in progress**: a request of the approval is pending or returned on + * the record, or a run is parked at a pause a step can follow (a node + * of the set the request carries) and is not waiting, through its child + * runs, on the step last decided. Nothing is written, and the mark + * stays. + * - **finished**: every run completed, stopped on a node outside the set, + * or is parked at a pause outside it, and no failure a run routed, nor a + * later step that could not open, ended the approval between two steps. + * The mirror writes the decision of the approval's latest request on the + * record, where that request was decided and its decision was held back, + * in the name of whoever decided it ({@link attributedMirrorContext}). + * - **abandoned**: a run ended between two steps ({@link abandonApproval}). + * - **cannot tell**: another process is advancing a run, a run or the + * table cannot be read, or, within the age bound, a run has no row, a + * run's step log is cut, the approval's runs number more than one + * judgement reads, or the latest request's own run is still parked at + * its own node. Nothing is written, and the mark stays for the + * reconciler. + * + * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last four + * have stopped at the step last decided, once two judgements in a row + * read the same of the same run (S14 of delta review 7269135624; + * {@link stoodState}), and the first of the two cannot tell (rulings A3 + * and B2 on #37767; a tree of more runs than one judgement reads, once a + * judgement keeps no run the approval had not kept, S11 of contract + * review 7266979193): where + * a step can follow it, the approval is abandoned and a run still parked + * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); + * where none can, it is finished, and once its outcome is on the record the + * administrators are told that its flow could not be seen through to its + * end after its last step + * ({@link reportFlowNotContinued}; ruling 3 on #37767: the outcome and the + * notice in one stroke, so a refused write sends no notice, and the pass on + * which the write lands sends it). + * + * In an approval that holds nothing back, finished and abandoned both end + * the hold: the mark is cleared and nothing is written, cancelled or told; + * where a run was placed, a line in the log says so. Where the approval's + * latest request was recalled, the writer that recalled it already wrote + * what an abandoned approval leaves: the mark is cleared and nothing more is + * written. Where no request of the approval carries the mark, it was judged + * already, and nothing is done. The marks are cleared once the outcome or + * the put-back lands; a write a rule or a hook of the app refused leaves + * them, so that the reconciler tries it again. + * + * Best-effort and never throws: the door's own action is durable before + * this runs. + */ + private async judgeApprovalAfterDoor( + request: { id?: unknown } | null | undefined, + door: string, + decided?: { requestId: string; actorId: string | null }, + opts?: { ageBoundMs?: number }, + ): Promise { + const requestId = request?.id != null ? String(request.id) : ''; + if (!requestId) return 'unstamped'; + try { + const own = await this.engine.find('sys_approval_request', { + where: { id: requestId }, limit: 1, context: SYSTEM_CTX, }); - organization = this.recordOrgResolver.organizationOf(object, Array.isArray(rows) ? rows[0] : undefined); - } - if (!organization && requestOrg != null && String(requestOrg) !== '') organization = String(requestOrg); - return { isSystem: true, userId: actorId, ...(organization ? { tenantId: organization } : {}) }; - } + const row: any = Array.isArray(own) ? own[0] : undefined; + const stamp = stampOf(row); + if (!row || stamp === undefined || !row.root_run_id) return 'unstamped'; - /** - * Re-read a business record's CURRENT state by id so approver resolution binds - * to live data at node entry, not the trigger snapshot the flow froze into - * `$record` at submit time (#3447). A `field` / `manager` approver names *who* - * decides, and an earlier node — or the approver of an earlier step — may have - * written that routing field after submit (e.g. a lead reviewer picking which - * departments co-review). Graph approvers (team / position / …) already query - * live; this brings the in-record types into line. - * - * Read under system identity: approver routing is a platform concern and the - * record is the flow's own subject, so the submitter's RLS/FLS must not narrow + const approval: any[] = (await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + orderBy: [{ field: 'created_at', order: 'desc' }], + limit: 500, context: SYSTEM_CTX, + })) ?? []; + // Newest first, so the latest is in the window however many requests + // the approval has; read oldest first below. + approval.reverse(); + // Open: a pending request, or a returned one in its revise window, which + // is the approval's latest (a resubmitted round stays `returned`). + const latest = approval[approval.length - 1] ?? row; + if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') { + // [the seat's reading 7257555103 of ruling A3, point 1] "At each + // door" is literal: a door that leaves a request open still reads the + // runs it can reach and keeps what it read, so that a child run that + // ended in this passage is read before its row can be trimmed. The + // answer of the reading is not used: an open request is in progress. + // Nor are the states it read kept (S14 of delta review 7269135624): + // this is no judgement, and a run parked at the step of a request + // that is still open has not stopped there. What it keeps carries no + // such state, so a judgement after it reads them anew. + try { + const read = (await this.readCarryingRun(latest, stamp, approval)).kept; + await this.keepRunsRead(latest, approval, read && { + ended: read.ended, open: read.open, ...(read.between ? { between: read.between } : {}), + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs at a door that left a request open; the next door reads them', { + request: requestId, error: err?.message ?? String(err), + }); + } + return 'in_progress'; + } + const marked = approval.filter(isMarked); + if (marked.length === 0) return 'judged'; + if (latest.status !== 'approved' && latest.status !== 'rejected') { + await this.clearMarks(marked); + return 'judged'; + } + + // The reconciler's age bound: every mark of the approval has stood past + // it. A state that says a run has stopped then places the run, where + // the judgement before read the same ({@link stoodState}). + const now = this.clock.now().getTime(); + const aged = opts?.ageBoundMs != null && marked.every((r) => { + const at = new Date(r.unjudged_since).getTime(); + return Number.isFinite(at) && now - at >= opts.ageBoundMs!; + }); + const reading = await this.readCarryingRun(latest, stamp, approval, aged); + // [ruling A3 on #37767] What the runs showed is kept on the approval's + // latest request, whatever the answer, so that a later judgement does + // not need those runs again. + await this.keepRunsRead(latest, approval, reading.kept); + if (reading.answer === 'undetermined') { + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} could not be judged yet: ${reading.why} ` + + 'Nothing was written; the request keeps its mark, and the reconciler judges it.', + { request: requestId, latest: latest.id, run: reading.runId ?? null }, + ); + return 'undetermined'; + } + if (reading.answer === 'in_progress') return 'in_progress'; + + const config = parseJson(latest.node_config_json, { approvers: [] } as any); + const field = typeof config.approvalStatusField === 'string' && config.approvalStatusField + ? config.approvalStatusField : undefined; + const holds = !!field && this.holdsBackDecision(latest, field); + // [rulings A3 and B2 on #37767, one rule] Past the age bound, a run that + // cannot be read, or the latest request's own run still parked at its + // own node, has stopped at the step last decided: where a step can + // follow it, the approval ended between two steps; where none can, it + // is finished, and the administrators are told that its flow did not + // go on after its last step. + let lastStepStopped: string | undefined; + let parkedRun: string | undefined; + let answer: 'finished' | 'abandoned' = reading.answer === 'placed' ? 'finished' : reading.answer; + let why = reading.answer === 'abandoned' || reading.answer === 'placed' ? reading.why : ''; + if (reading.answer === 'placed') { + const stepNode = String(latest.flow_node_id ?? latest.current_step ?? ''); + // The flow the step stands in: the parked run's where a run is still + // parked at it, otherwise the one its request records, so that a + // node of another flow of the set that carries the step's id does + // not answer for it (N20 of contract review 7266979193). + const stepFlow = reading.flow ?? flowNameOfProcess(latest.process_name); + if (stepNode && standsBetweenSteps(stamp, stepFlow, stepNode)) { + answer = 'abandoned'; + parkedRun = reading.parkedRun; + } else { + lastStepStopped = reading.why; + } + why = reading.why; + if (!holds) { + // Nothing was held back, so nothing is written, cancelled or told: + // the log keeps what was concluded of a run that did not go on. + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} is over, and held nothing back: ${reading.why} ` + + 'Its marks were cleared; nothing was written, cancelled or told.', + { request: requestId, latest: latest.id, run: reading.parkedRun ?? null }, + ); + } + } + if (answer === 'finished') { + if (!holds) { + await this.clearMarks(marked); + return 'finished'; + } + const actor = decided && decided.requestId === String(latest.id) + ? decided.actorId + : await this.deciderOf(latest); + const refusal = await this.mirrorStatusField( + latest.object_name, latest.record_id, field!, String(latest.status), actor, + latest.organization_id ?? null, undefined, { request: latest, step: latest.flow_node_id ?? latest.current_step ?? null }, + ); + // [ruling 3 on #37767] The outcome and the administrators' notice in + // one stroke. A refused write keeps the marks and sends no notice + // that the flow could not be seen through to its end (the mirror + // reports its refusal); the pass on which the write lands sends it. + if (!refusal) { + if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); + await this.clearMarks(marked); + } + return 'finished'; + } + if (!holds) { + await this.clearMarks(marked); + return 'ended'; + } + await this.abandonApproval(latest, marked, field!, why); + // [ruling B2] The run parked at the decided step is cancelled, with the + // runs that wait on it, so that nothing resumes the approval on a + // record that was put back. + if (parkedRun) await this.cancelStoppedRun(latest, parkedRun, why); + return 'abandoned'; + } catch (err: any) { + this.logger?.warn?.( + `[approvals] after ${door}, the approval of request '${requestId}' could not be judged: ${err?.message ?? err}. ` + + 'Nothing was written; its marks stand, and the reconciler judges it.', + { request: requestId, error: err?.message ?? String(err) }, + ); + return 'undetermined'; + } + } + + /** + * [ADR-0162 D5, Execution item 8] Read every run of the approval and place + * where each stopped against `stamp`. The walk starts at the run that + * carries the record, the latest request's own run, and every run the + * approval kept as read to its end over a child not read yet (`open`, + * {@link RunsRead}), and follows the child runs each delegating step + * records (`childRunIds` on the step log): every `subflow` child, and every + * `map` item run that does not carry another record (an item that is a + * record carries an approval of its own). A run kept as ended is not read + * again: what it showed is in the kept reading, and every run below it was + * read to its end before it was kept ({@link keptAsEnded}). + * + * It reads the whole tree before it answers, so that no run it could read + * is left out of what it keeps, and one run's answer does not hide + * another's. A run it cannot read ends the reading at once, since nothing + * can be concluded past it: + * + * - A run that cannot be read because the store did not answer, that + * another process is advancing, or that reports paused with no pause to + * be found (within the age bound, and past it where the judgement + * before did not read it so): `undetermined`. + * - A tree of more runs than one judgement reads + * ({@link MAX_RUNS_READ_PER_APPROVAL}): `undetermined` within the age + * bound, and past it while this reading keeps a run the approval had + * not kept and that reading is on the request, so that the next + * judgement reads on from it. The reading that keeps none cannot + * finish the tree: it answers from the runs it did read, and where + * they say nothing it is `placed`, as below. + * - Otherwise, a run parked at a node of the set that is not waiting on + * the step last decided: `in_progress`. A run parked there on a child + * run says what its child says ({@link ApprovalService.waitingRun}): the + * walk reads the child, down to the latest request's own run where that + * is what the runs above it wait on. + * - Otherwise, a failure between two steps that no later request answered, + * read now or kept, or a later step that could not open (the note on + * `latest`, read once the runs are read, {@link laterStepNotOpenedOn}): + * `abandoned`. + * - Otherwise, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}: the runs it leaves out cannot be + * read), a tree this reading could not finish, or the latest request's + * own run still parked at its own node: within the bound + * `undetermined`; past it `placed` where the judgement before read + * every such state of this reading too, and `undetermined` where it + * did not. Placed, the run has stopped at the step last decided + * (rulings A3 and B2 on #37767, one rule), and + * {@link judgeApprovalAfterDoor} ends the approval by whether a step can + * follow that step. + * - Otherwise `finished`. + * + * A run with no row is spoken for where a run that was read went on past + * the step that names it (the seat's reading 7257555103 of ruling A3; + * {@link childRunsOf}, {@link passedWithNoRow}): it counts as passed at + * that step, and is kept as ended. A continuation along a failure route is + * not going on past the step, and a log that is cut speaks for no run. + * + * A failure between two steps is a failure the flow routed, of a node of + * the set at the top level of a run (N46 c′: a failure handled in a + * `try_catch` region is the author's statement that it needs no later + * step), or a run that ended on a node of the set ({@link stopOf}); it is + * answered where a request of the approval opened after it. An end after + * the last step is the approval's end, also where a node after the last + * step failed. + * + * `aged` is the reconciler's: every mark of the approval has stood past + * {@link RECONCILER_AGE_BOUND_MS}. Then a run that reports paused while its + * pause is gone is read as stopped at its last step, and a run parked at a + * `subflow` or a `map` whose child run has ended (an item run that carries + * another record included), has no row or will not go on itself, as + * stopped at that node. + * + * Each of these, and each state that places the approval by the step last + * decided, is also what a run the engine is advancing reads as, and the + * bound is counted from the marks, not from the run's last movement. So a + * state stands only where the judgement before this one read it too, for + * the same run (S14 of delta review 7269135624; {@link stoodState}): the + * reading that meets a state first answers `undetermined`, or + * `in_progress` for a run parked on a child that has ended, and keeps the + * state. Every reading keeps the states it read, aged or not, in place of + * those kept before; a reading that reaches none keeps none. + * + * Every answer carries `kept`: the kept reading with what this reading + * found ({@link runsReadAfter}), which the door writes on the latest + * request. A reading that ended early keeps what it had read by then. + */ + private async readCarryingRun( + latest: any, + stamp: readonly StampedNode[], + approval: readonly any[], + aged = false, + ): Promise< + | { answer: 'undetermined'; why: string; runId?: string; kept?: RunsRead } + | { answer: 'in_progress'; kept?: RunsRead } + | { answer: 'finished'; kept?: RunsRead } + | { answer: 'abandoned'; why: string; kept?: RunsRead } + | { answer: 'placed'; why: string; parkedRun?: string; flow?: string; kept?: RunsRead } + > { + const rootId = String(latest.record_run_id ?? latest.root_run_id ?? ''); + const automation = this.automation; + if (!rootId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; + if (typeof automation?.getRun !== 'function') { + return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId: rootId }; + } + + const lastOpened = approval.reduce((acc, r) => { + const at = instantOf(r?.created_at); + return Number.isFinite(at) && at > acc ? at : acc; + }, -Infinity); + const ownRuns = new Set(approval.map((r) => (r?.flow_run_id != null ? String(r.flow_run_id) : '')).filter(Boolean)); + const prior = runsReadOf(approval); + const settled = new Set(prior.ended); + const found = noRunsFound(); + let between = prior.between && !(instantOf(prior.between.at) < lastOpened) ? prior.between : undefined; + const kept = (): RunsRead => runsReadAfter(prior, found, between); + // [S14 of delta review 7269135624] A state that says a run has stopped + // stands only where the judgement before this one read it too, for the + // same run: the engine may be advancing the run, and then the state + // clears within that passage. Every such state this reading reads is + // kept for the next judgement, whatever this one answers. + const stoodBefore = new Set(prior.stood ?? []); + const stands = (state: string): boolean => { + found.stood.add(state); + return aged && stoodBefore.has(state); + }; + + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (ownRunId && ownRunId !== rootId) queue.push({ id: ownRunId, item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); + /** What each run read in this walk answered, in the order read. */ + const read = new Map(); + /** The first run read whose step log is cut ({@link stepLogCut}). */ + let cutLog: { runId: string; why: string } | undefined; + /** Every run read whose step log is cut. */ + const cutRuns: string[] = []; + /** The first run this reading did not get to: the tree holds more runs than one judgement reads. */ + let unread: string | undefined; + while (queue.length > 0) { + const next = queue.shift()!; + const runId = next.id; + if (next.passed) found.passed.add(runId); + if (read.has(runId) || settled.has(runId)) continue; + if (read.size >= MAX_RUNS_READ_PER_APPROVAL) { + // No further run is read. The queue is still emptied, so that every + // run a run that was read went on past counts as passed. + unread ??= runId; + continue; + } + const one = await this.readApprovalRun(runId, { + stamp, lastOpened, aged, stands, item: next.item && !ownRuns.has(runId), latest, + }); + read.set(runId, one); + if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; + if (one.answer === 'no_row') { + found.noRow.add(runId); + continue; + } + if (one.answer === 'foreign') { + // Kept as ended once it has ended. One that has not is not kept: the + // batch above it is read again, and reads it again. + if (one.over) found.foreign.add(runId); + continue; + } + // A run whose log is cut names its children in part: they are read, + // and it is never kept as ended ({@link keptAsEnded} wants its children). + if (one.cut === undefined) found.childrenOf.set(runId, one.children.map((c) => c.id)); + else { + cutLog ??= { runId, why: one.cut }; + cutRuns.push(runId); + } + if (one.answer === 'read' && one.over) { + found.terminal.add(runId); + if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; + } + queue.push(...one.children); + // The child a parked run waits on is read as well, also where no step + // names it; and it is read next, so that what a parked run waits on is + // read before the runs beside it use up the reading. + if (one.answer === 'waits') queue.unshift({ id: one.on, item: one.item, passed: false }); + } + + const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); + let inProgress = false; + let endedWhy: string | undefined; + let parkedAtOwnNode: { runId: string; flow?: string } | undefined; + for (const [runId, one] of read) { + if (one.answer === 'in_progress') { + inProgress = true; + } else if (one.answer === 'own_node') { + parkedAtOwnNode = { runId, flow: one.flow }; + } else if (one.answer === 'read') { + endedWhy ??= one.endedWhy; + } else if (one.answer === 'waits') { + const says = this.waitingRun(runId, read, settled, stands); + // A child the reading did not get to says nothing of the run parked + // on it: in a tree that cannot be finished, it is not in progress. + if (says === 'moving' || (says === 'unread' && unread === undefined)) inProgress = true; + else if (typeof says !== 'string') endedWhy ??= says.why; + } + } + // The states that place the approval by the step last decided. Each is + // read here, before any answer, so that it is kept for the next + // judgement also where this one answers something else; and the + // approval is placed only where every one of them stood before + // ({@link stoodState}). + const placing = [ + ...(parkedAtOwnNode ? [stoodState('own_node', parkedAtOwnNode.runId)] : []), + ...cutRuns.map((id) => stoodState('cut', id)), + ...(unread !== undefined ? [stoodState('tree', rootId)] : []), + ...missing.map((id) => stoodState('no_row', id)), + ]; + const allStood = placing.map(stands).every(Boolean); + + // [S11 of contract review 7266979193] A tree of more runs than one + // judgement reads has an end. Within the age bound the next judgement + // reads on. Past it, it reads on only where this reading kept a run the + // approval had not kept, and that reading is on the request: the kept + // list only grows and holds at most MAX_RUNS_READ_PER_APPROVAL runs, so + // the judgements that read on are numbered. The reading that keeps none + // cannot finish the tree, and answers below from the runs it did read. + if (unread !== undefined) { + const reading = kept(); + const readsOn = !aged + || (reading.ended.length > prior.ended.length && await this.keepRunsRead(latest, approval, reading)); + if (readsOn) { + return { + answer: 'undetermined', runId: unread, kept: reading, + why: `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads; the runs read to their end are kept, and the next judgement reads on.`, + }; + } + } + + if (inProgress) return { answer: 'in_progress', kept: kept() }; + const notOpened = await this.laterStepNotOpenedOn(latest); + if (notOpened) { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + kept: kept(), + }; + } + const failed = endedWhy ?? between?.why; + if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; + if (placing.length > 0) { + const what = parkedAtOwnNode + ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` + : cutLog + ? `the step log of its run '${cutLog.runId}' does not name every child run it started (${cutLog.why}), so the runs below it cannot all be read` + : unread !== undefined + ? `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads, and this judgement kept no further run as read to its end, so its runs (the run '${unread}' among them) cannot all be read` + : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; + const runId = parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0]; + if (!aged) { + return { + answer: 'undetermined', runId, kept: kept(), + why: parkedAtOwnNode || !cutLog ? `${what}, and a process may still be moving it.` : `${what}; within the age bound nothing is concluded from it.`, + }; + } + if (!allStood) { + return { + answer: 'undetermined', runId, kept: kept(), + why: `${what}; the judgement before this one did not read the same, so a process may be moving it, and the next judgement places it if it still reads so.`, + }; + } + return { + answer: 'placed', + why: `${what}; past the age bound it has stopped at that step.`, + ...(parkedAtOwnNode ? { parkedRun: parkedAtOwnNode.runId, flow: parkedAtOwnNode.flow } : {}), + kept: kept(), + }; + } + return { answer: 'finished', kept: kept() }; + } + + /** + * [ADR-0162 Execution item 8, S6 of contract review 7257527251] The note + * that a later step of `latest`'s approval could not open + * ({@link noteLaterStepNotOpened}), read from the row now and not from the + * copy the judgement began with. A passage writes the note before its run + * ends or parks, so a judgement that reads it once the runs are read + * cannot answer from runs that are still over a note it has not seen. + */ + private async laterStepNotOpenedOn(latest: any): Promise<{ node?: unknown; reason?: unknown } | undefined> { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const row: any = (Array.isArray(rows) ? rows[0] : undefined) ?? latest; + const note = parseJson>(row.node_config_json, {})[LATER_STEP_NOT_OPENED_KEY]; + return note && typeof note === 'object' ? note as { node?: unknown; reason?: unknown } : undefined; + } + + /** + * [ADR-0162 D5, Execution item 8] What a run parked at a node of the set on + * a child run says of the approval, once the walk has read that child + * ({@link readCarryingRun}). A parked parent moves only when its child + * does, so it says what the child says: + * + * - `moving`: the child is in progress in its own right, is parked at a + * pause that is not of the set, or carries another record and has not + * ended; or the child has ended or has no row, and the engine may still + * be resuming the parent: within the age bound, and past it where the + * judgement before did not read the parent parked on that same child + * so ({@link stoodState}). The approval is in progress. + * - `unread`: the reading did not get to the child, so the parent says + * nothing. The caller reads it as moving, except in a tree of more runs + * than one judgement reads ({@link readCarryingRun}). + * - `still`: the child is the latest request's own run, parked at the step + * its decision was recorded on, or a run that waits on that run in turn. + * The parent says nothing of its own: the one rule places the approval + * by that step (B2 on #37767), at whatever depth the step sits. + * - `{ why }`: past the age bound, and as the judgement before read it, + * the child has ended, has no row, or reports paused at a pause that is + * gone, so nothing will resume the parent, between two steps. An item + * run of a `map` that carries another record has ended once it is in a + * terminal status (S12 of contract review 7266979193). + */ + private waitingRun( + runId: string, + read: ReadonlyMap, + settled: ReadonlySet, + stands: (state: string) => boolean, + above: ReadonlySet = new Set(), + ): 'moving' | 'still' | 'unread' | { why: string } { + const parent = read.get(runId); + if (parent?.answer !== 'waits' || above.has(runId)) return 'moving'; + const child = read.get(parent.on); + const stopped = (how: string) => ({ + why: `its run '${runId}' is parked at '${parent.node}' on a child run that ${how}, so nothing will resume it, between two steps.`, + }); + // Between a child's end and the resume of the run parked on it, the + // engine has not claimed the parent's pause yet: the state stands only + // where the judgement before read it too ({@link stoodState}). + const ended = () => (stands(stoodState('on_ended', runId, parent.on)) ? stopped('has ended') : 'moving' as const); + if (!child) return settled.has(parent.on) ? ended() : 'unread'; + switch (child.answer) { + case 'no_row': return ended(); + case 'foreign': return child.over ? ended() : 'moving'; + case 'own_node': return 'still'; + case 'waits': { + const says = this.waitingRun(parent.on, read, settled, stands, new Set([...above, runId])); + return typeof says === 'string' ? says : stopped('will not go on'); + } + case 'read': + if (child.over) return ended(); + return child.stopped ? stopped('will not go on') : 'moving'; + default: return 'moving'; + } + } + + /** + * [ADR-0162 D5, Execution item 8] One run of an approval's tree, for + * {@link readCarryingRun}: whether it can be read and is still, whether it + * is parked between two steps or at the latest request's own node, whether + * it is over (a terminal status) and ended between two steps, and the + * child runs to read next. `item`: the run is an item run of a `map` that + * is not the run of a request of the approval; one that carries a record + * other than the approval's is `foreign`: it is not followed, and only + * whether it has ended is read. + */ + private async readApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + ): Promise { + const log: { cut?: string } = {}; + const one = await this.placeApprovalRun(runId, at, log); + return log.cut !== undefined && 'children' in one ? { ...one, cut: log.cut } : one; + } + + /** The body of {@link readApprovalRun}; `log.cut` is set where the run's step log is cut ({@link stepLogCut}). */ + private async placeApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + log: { cut?: string }, + ): Promise { + const { stamp, lastOpened, aged, stands, item, latest } = at; + const automation = this.automation!; + let run: { + status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null; + try { + run = await automation.getRun!(runId, { strict: true }); + } catch (err: any) { + return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).` }; + } + if (!run) return { answer: 'no_row' }; + if (item) { + const object = run.trigger?.object; + const record = run.trigger?.recordId; + if (record != null && record !== '' && (String(record) !== String(latest.record_id) || (object != null && String(object) !== String(latest.object_name)))) { + return { answer: 'foreign', over: typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status) }; + } + } + const status = typeof run.status === 'string' ? run.status : ''; + if (!status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.` }; + if (ADVANCING_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.` }; + } + const flow = typeof run.flowName === 'string' ? run.flowName : undefined; + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + log.cut = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)); + const speaks = log.cut === undefined; + let children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, speaks); + + // A failure the flow routed, at the top level of the run, on a node of + // the set, after which no request of the approval opened. Read for a + // paused run as for an ended one: a failure routed to a pause outside + // the set ended the approval as surely as one routed to an end. + const routedFailure = (stop: string | undefined) => steps.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stop + && standsBetweenSteps(stamp, flow, s.nodeId) + && !(instantOf(s.startedAt) < lastOpened)); + const routedWhy = (s: RunStepRead) => `its node '${String(s.nodeId)}' failed between two steps, and the flow went on without asking the next step.`; + + if (status === 'paused') { + let parked: { nodeId?: string; flowName?: string; correlation?: string } | undefined; + try { + parked = await automation.suspensionOf?.(runId); + } catch (err: any) { + return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).` }; + } + if (!parked?.nodeId) { + // What a run the engine is advancing reads as, too: its pause is + // consumed, and it has not parked again or ended. It has stopped + // only where the judgement before read it so as well (S14). + if (!stands(stoodState('pause_gone', runId))) { + return { + answer: 'undetermined', + why: aged + ? `the run '${runId}' reports paused, and no pause of it can be found; the judgement before this one did not read the same, so a process may be resuming it, and the next judgement places it if it still reads so.` + : `the run '${runId}' reports paused, and no pause of it can be found.`, + }; + } + const stop = stopOf(steps, 'failed'); + const routed = routedFailure(stop); + if (routed) return { answer: 'read', over: false, stopped: true, endedWhy: routedWhy(routed), children }; + return { + answer: 'read', over: false, stopped: true, children, + ...(stop && standsBetweenSteps(stamp, flow, stop) + ? { endedWhy: `its run '${runId}' reports paused at a pause that is gone, so it will not go on, between two steps.` } + : {}), + }; + } + // The run did not go on past the node it is parked at. + children = childRunsOf(steps, false, parked.nodeId, speaks); + // [ruling B2 on #37767] The latest request's own run, still parked at + // the node its decision was recorded on: the run was not resumed. + if (String(runId) === String(latest.flow_run_id ?? '') && parked.nodeId === String(latest.flow_node_id ?? '')) { + return { answer: 'own_node', flow: parked.flowName ?? flow, children }; + } + if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) { + // Parked between two steps. On a child run, it says what the child + // says, and the walk reads the child ({@link waitingRun}); on + // anything else, a step can still follow. + const correlation = typeof parked.correlation === 'string' ? parked.correlation : ''; + const child = childOfCorrelation(correlation); + return child + ? { answer: 'waits', on: child, item: correlation.startsWith('map:'), node: parked.nodeId, children } + : { answer: 'in_progress', children }; + } + // Parked outside the set (M3 of 7255916895): a routed failure before + // the pause still ended the approval between two steps. + const routed = routedFailure(undefined); + return { answer: 'read', over: false, children, ...(routed ? { endedWhy: routedWhy(routed) } : {}) }; + } + if (!TERMINAL_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` }; + } + + const stop = stopOf(steps, status); + const routed = routedFailure(stop); + if (routed) { + return { answer: 'read', over: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; + } + if (REACHED_AN_END.has(status)) return { answer: 'read', over: true, children }; + // A run that ended before the approval's latest request opened did not + // stop it: the approval went on. + const answered = instantOf(run.completedAt) < lastOpened; + const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; + if (!stop) { + return { answer: 'read', over: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; + } + if (!answered && standsBetweenSteps(stamp, flow, stop)) { + return { answer: 'read', over: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; + } + return { answer: 'read', over: true, children }; + } + + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] Keep `kept` on + * `latest`'s snapshot ({@link RUNS_READ_KEY}), where it differs from what + * the approval kept; `latest` is updated in place, so a later write of its + * snapshot in the same judgement carries it. + * + * The reading is a cache of what the runs showed, and the snapshot also + * holds facts other writers leave between this judgement's read of the row + * and this write: the note that a later step could not open + * (`__laterStepNotOpened`) and the journal of a failed resume + * (`__strandedContinuation`). So it writes its own key only, onto the + * snapshot read again just before the write, and the write is conditional: + * it lands only while the column still reads what the key was set on. A + * write that finds the column changed reads it again, at most + * {@link KEEP_RUNS_READ_ATTEMPTS} times. It can therefore not write a + * stale snapshot over another writer's note, whenever that note lands. + * + * Best-effort: a reading that is not kept leaves the runs to be read + * again, and leaves on the request the reading kept before it, its states + * included ({@link stoodState}). The next judgement stands on that + * earlier reading, which is not the one before it: where it holds the + * same state for the same run, the run is placed on it; where it holds + * none, nothing is placed. So an approval whose reading is never kept is + * held with no end (N29 of delta review 7270552441). The condition of the + * write is the column as read just before it, so of two judgements at + * once the one that read first can write last. It answers whether `kept` + * is on the approval's rows now, which a judgement that relies on the + * next one reading on from it asks ({@link readCarryingRun}); the + * judgement that places a state does not ask. + */ + private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { + if (!kept || !latest?.id) return false; + if (sameRunsRead(runsReadOf(approval), kept)) return true; + try { + for (let attempt = 0; attempt < KEEP_RUNS_READ_ATTEMPTS; attempt++) { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const current: any = Array.isArray(rows) ? rows[0] : undefined; + if (!current) return false; + const before: unknown = current.node_config_json; + const node_config_json = JSON.stringify({ ...parseJson>(before, {}), [RUNS_READ_KEY]: kept }); + // The predicate form: the engine answers how many rows it wrote. + const landed = await this.engine.update('sys_approval_request', { node_config_json }, { + where: { id: latest.id, node_config_json: typeof before === 'string' ? before : { $null: true } }, + multi: true, context: SYSTEM_CTX, + }); + if (Number(landed) > 0) { + latest.node_config_json = node_config_json; + return true; + } + } + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs: its request\'s snapshot kept changing under the write; the next judgement reads them again', { + request: latest.id, + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs; the next judgement reads them again', { + request: latest.id, error: err?.message ?? String(err), + }); + } + return false; + } + + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What a request that is + * opening keeps of its approval's runs: what the plugin can read from the + * run that carries the record, the request's own run and the runs the + * approval kept as open, down the child runs their steps name, kept by the + * rule every reading keeps by ({@link runsReadAfter}): a run is kept as + * ended only once every child it names is. Every failure before this + * opening is answered by it, so none is kept. A run being advanced is read + * from what it logged when it last paused, so the run opening the + * approval's first request, which has logged nothing yet, is read at the + * first door. `undefined` where nothing is kept. Best-effort and never + * throws: a run it cannot read is read at the next door. + */ + private async runsReadAtOpening(row: { + root_run_id?: unknown; record_run_id?: unknown; flow_run_id?: unknown; object_name?: unknown; record_id?: unknown; + }): Promise { + const rootId = String(row.record_run_id ?? row.root_run_id ?? ''); + if (!rootId || !row.root_run_id || typeof this.automation?.getRun !== 'function') return undefined; + try { + const approval: any[] = (await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'flow_run_id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + })) ?? []; + const prior = runsReadOf(approval); + const settled = new Set(prior.ended); + const ownRuns = new Set([...approval.map((r) => String(r?.flow_run_id ?? '')), String(row.flow_run_id ?? '')].filter(Boolean)); + const found = noRunsFound(); + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (row.flow_run_id && String(row.flow_run_id) !== rootId) queue.push({ id: String(row.flow_run_id), item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); + const seen = new Set(); + while (queue.length > 0 && seen.size < MAX_RUNS_READ_PER_APPROVAL) { + const { id, item, passed } = queue.shift()!; + if (passed) found.passed.add(id); + if (seen.has(id) || settled.has(id)) continue; + seen.add(id); + let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null; + try { + run = await this.automation.getRun(id, { strict: true }); + } catch { + continue; + } + if (!run) { + found.noRow.add(id); + continue; + } + const record = run.trigger?.recordId; + const status = typeof run.status === 'string' ? run.status : ''; + if (item && !ownRuns.has(id) && record != null && record !== '' + && (String(record) !== String(row.record_id) || (run.trigger?.object != null && String(run.trigger.object) !== String(row.object_name)))) { + // An item run of another record is kept as ended once it has ended. + if (TERMINAL_RUN_STATUSES.has(status)) found.foreign.add(id); + continue; + } + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + // A cut log names its children in part and speaks for none: its run is not kept as ended. + const whole = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)) === undefined; + const children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, whole); + if (whole) found.childrenOf.set(id, children.map((c) => c.id)); + if (TERMINAL_RUN_STATUSES.has(status)) found.terminal.add(id); + queue.push(...children); + } + const kept = runsReadAfter(prior, found, undefined); + return kept.ended.length === 0 && kept.open.length === 0 ? undefined : kept; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs as its request opened; the next door reads them', { + error: err?.message ?? String(err), + }); + return undefined; + } + } + + /** + * [ADR-0162 D5, Execution item 8] Abandon an approval whose run ended + * between two steps, for its record, once no request of it is open. The + * decisions already made stay on their requests, with who decided and when. + * + * 1. The approval is marked abandoned on its latest request (`__abandoned` + * on its snapshot), first, so that the door that continues a restored + * run refuses it however far the rest gets ({@link continueRestoredRun}). + * 2. The mirror writes what an abandoned approval leaves, by item 7's + * order ({@link abandonedValueOnClosingField}): `recalled` where the + * field declares it and the object does not close on it, otherwise the + * value at submit, the default or empty, never a closed value. Where a + * request of another approval is pending or returned on the record and + * mirrors onto the same field, it writes nothing: the field is that + * approval's now. + * 3. A line with no actor on the latest request's timeline says that the + * approval did not go on, why, and what the record was put back to. + * 4. The submitter is told, and submits again. + * + * The marks are cleared where the put-back landed or nothing was to be + * written; a put-back a rule or a hook of the app refused is reported by the + * mirror and leaves them, for the reconciler to try again. + */ + private async abandonApproval(latest: any, marked: readonly any[], field: string, why: string): Promise { + const now = this.clock.now().toISOString(); + const object = String(latest.object_name); + const recordId = String(latest.record_id); + const org = latest.organization_id ?? null; + const step = latest.flow_node_id ?? latest.current_step ?? null; + + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [ABANDONED_KEY]: { at: now, reason: why } }), + }, { context: SYSTEM_CTX }); + + let other: any; + try { + const open = await this.engine.find('sys_approval_request', { + where: { object_name: object, record_id: recordId, status: { $in: ['pending', 'returned'] } }, + limit: 50, context: SYSTEM_CTX, + }); + for (const r of Array.isArray(open) ? open : []) { + if (String(r?.root_run_id ?? '') === String(latest.root_run_id ?? '')) continue; + if (parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField !== field) continue; + // A returned request is open only in its revise window: no later + // request of its approval on the record (a resubmitted round stays + // `returned`). + if (r.status === 'returned') { + const later = await this.engine.find('sys_approval_request', { + where: r.root_run_id + ? { root_run_id: r.root_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } } + : { flow_run_id: r.flow_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(later) && later.length > 0) continue; + } + other = r; + break; + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether another approval is open on the record of an abandoned one; the put-back goes ahead', { + request: latest.id, object, record: recordId, error: err?.message ?? String(err), + }); + } + + let refusal: MirrorRefusal | undefined; + let left: string; + if (other) { + left = `The record's ${field} was left as it is: the request '${String(other.id)}' of another approval is open on it.`; + } else { + refusal = await this.mirrorStatusField( + object, recordId, field, 'recalled', null, org, + { payloadJson: latest.payload_json }, { request: latest, step }, + ); + if (refusal) { + left = `The record's ${field} could not be put back: ${refusal.message}`; + } else { + let value: unknown; + try { + const rows = await this.engine.find(object, { where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX }); + value = Array.isArray(rows) ? rows[0]?.[field] : undefined; + } catch { value = undefined; } + left = value == null || value === '' + ? `The record's ${field} was put back to empty.` + : `The record's ${field} was put back to '${String(value)}'.`; + } + } + + try { + // A put-back the reconciler tries again leaves its line once. + if (!(await this.hasTimelineLine(String(latest.id), abandonedNoteText(why, left)))) { + await this.engine.insert('sys_approval_action', await this.actionRow(latest, { + id: uid('aact'), request_id: latest.id, organization_id: org, + step_name: step, step_index: 0, action: 'comment', + actor_id: null, + comment: abandonedNoteText(why, left), + created_at: now, + }), { context: SYSTEM_CTX }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note an abandoned approval on its request timeline', { + request: latest.id, error: err?.message ?? String(err), + }); + } + this.logger?.warn?.( + `[approvals] the approval of ${object}/${recordId} ended between two steps and was abandoned: ${why} ${left} ` + + 'The decisions already made stay on their requests; the submitter was told, and submits again.', + { request: latest.id, object, record: recordId, field }, + ); + + if (latest.submitter_id) { + try { + await this.notify({ + topic: ABANDONED_APPROVAL_TOPIC, + organizationId: org, + audience: [String(latest.submitter_id)], + source: { object: 'sys_approval_request', id: String(latest.id) }, + dedupKey: `approval-abandoned-${String(latest.id)}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalAbandonedTitle', body: 'approvalAbandonedBody', params: subject, + }), + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the submitter of an abandoned approval', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + + if (!refusal) await this.clearMarks(marked); + } + + /** + * [ADR-0162 Execution item 8, ruling B2 on #37767] Cancel the run of an + * approval that was abandoned while the run stood parked at the step its + * decision was recorded on, and the runs above it that wait on it, up to + * the run that carries the record, deepest first: nothing resumes the + * approval on a record that was put back. + * + * The chain goes through a `map` as through a `subflow`. A `map` between + * the run that carries the record and the parked run has items that are + * not records, so its items are steps of this one approval: the batch is + * cancelled with its item, and is not woken to start the next item, which + * would open a step of the abandoned approval. (A batch whose items are + * records sits above the run that carries the record, and is not in the + * chain.) + * + * A cancel that fails is logged; the approval stays abandoned, and the + * door that continues a restored run refuses it. + */ + private async cancelStoppedRun(latest: any, runId: string, why: string): Promise { + if (typeof this.automation?.cancelRun !== 'function') { + this.logger?.warn?.('[approvals] no automation engine in this process can cancel the run of an abandoned approval; it stays parked', { + request: latest?.id, run: runId, + }); + return; + } + const chain = await this.voidedRunChain( + String(latest.id), runId, latest.record_run_id ? String(latest.record_run_id) : undefined, + 'whose approval was abandoned when its run did not go on', + { throughMap: true }, + ); + const reason = `the approval of request ${String(latest.id)} was abandoned: ${why}`; + for (const id of [...chain].reverse()) { + try { + await this.automation.cancelRun(id, reason); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not cancel a run of an abandoned approval; it may stay parked', { + request: latest.id, run: id, error: err?.message ?? String(err), + }); + return; + } + } + } + + /** + * [ADR-0162 Execution item 8, ruling B2 on #37767] Tell the organization's + * administrators that the approval of `latest`'s record was decided at its + * last step and its outcome written, while its flow could not be seen + * through to its end after that step, so the flow's nodes after it may not + * have run: the run did not go on, has no row, or could not be read in full + * (a cut step log, a tree of more runs than the judgements read). The + * notice asks for a check and states no failure (N19 of contract review + * 7266979193). The run's pause, where it has one, is left for an operator + * to continue or cancel. + * Sent once per request, and only on the pass whose outcome write landed + * (ruling 3 on #37767). + */ + private async reportFlowNotContinued(latest: any, why: string): Promise { + const object = String(latest.object_name); + const recordId = String(latest.record_id); + const org = latest.organization_id ?? null; + this.logger?.warn?.( + `[approvals] the approval of ${object}/${recordId} was decided at its last step, and its outcome was written, but ` + + `${why} The flow's nodes after that step may not have run; the organization's administrators were told.`, + { request: latest.id, object, record: recordId, run: latest.flow_run_id ?? null }, + ); + try { + const admins = await this.organizationAdministrators(org); + if ('ids' in admins && admins.ids.length) { + await this.notify({ + topic: FLOW_NOT_CONTINUED_TOPIC, + organizationId: org, + audience: admins.ids, + source: { object: 'sys_approval_request', id: String(latest.id) }, + dedupKey: `approval-flow-not-continued-${String(latest.id)}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalFlowNotContinuedTitle', body: 'approvalFlowNotContinuedBody', params: subject, + }), + }); + } else if ('failure' in admins) { + this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them a flow could not be seen through to its end after its last step', { + request: latest.id, organizationId: org, error: admins.failure, + }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators that a flow could not be seen through to its end after its last step', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 Execution item 8] Clear the mark on `rows`, one keyed update + * each: the approval they belong to has been judged, or their requests' + * approval has moved on, or a writer abandoned it. Best-effort: a mark that + * stays is judged again by the reconciler, which writes nothing twice. + */ + private async clearMarks(rows: readonly any[]): Promise { + for (const r of rows) { + if (!isMarked(r)) continue; + try { + await this.engine.update('sys_approval_request', { id: r.id, unjudged_since: null }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not clear the mark on a judged request; the reconciler judges it again', { + request: r.id, error: err?.message ?? String(err), + }); + } + } + } + + /** + * [ADR-0162 Execution item 8] Whether `requestId`'s timeline already holds a + * comment that reads `comment`, a sentence only the platform writes: a + * write the reconciler tries again on each pass reports its failure once. + * A read that fails answers `false`, and the line is left again. + */ + private async hasTimelineLine(requestId: string, comment: string): Promise { + try { + const rows = await this.engine.find('sys_approval_action', { + where: { request_id: requestId, action: 'comment', comment }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + return Array.isArray(rows) && rows.length > 0; + } catch { + return false; + } + } + + /** + * [ADR-0162 Execution item 8] Clear the marks on the requests of `row`'s + * approval on its record other than `row` itself. A recall, an override and + * the dead-run sweep abandon the approval at its open request, and the + * marks its earlier decisions left would otherwise hold the record. A new + * request of the approval, as it opens, ends the passage its earlier + * decisions began. No-op for a request of an approval that was not stamped. + */ + private async clearEarlierMarks(row: any): Promise { + if (stampOf(row) === undefined || !row?.root_run_id) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'unjudged_since'], limit: 500, context: SYSTEM_CTX, + }); + await this.clearMarks((Array.isArray(rows) ? rows : []).filter((r: any) => String(r.id) !== String(row.id))); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the marks of an approval\'s earlier requests; the reconciler judges them', { + request: row?.id, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 D5, Execution item 8] An abandoned approval does not go on. + * Refuse {@link continueRestoredRun} for a request of an approval the door + * or the reconciler marked abandoned on its record: an operator who put a + * failed run's pause back would otherwise open the next step on a document + * that has since been put back, and perhaps submitted again. The operator + * cancels the restored run instead. A read that fails refuses as well: the + * continuation is a repair, and it waits for a store that answers. + */ + private async refuseAbandonedContinuation(raw: any, requestId: string): Promise { + if (stampOf(raw) === undefined || !raw?.root_run_id) return; + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: raw.root_run_id, object_name: raw.object_name, record_id: raw.record_id }, + fields: ['id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + }); + const abandoned = (Array.isArray(rows) ? rows : []).find((r: any) => + parseJson>(r?.node_config_json, {})[ABANDONED_KEY] !== undefined); + if (!abandoned) return; + const runId = String(raw.flow_run_id ?? ''); + throw new Error( + `INVALID_STATE: the approval of ${String(raw.object_name)}/${String(raw.record_id)} that request ${requestId} ` + + `belongs to was abandoned when its run ended between two steps (request '${String(abandoned.id)}'), and its ` + + `record was put back, so it does not go on. Cancel the restored run '${runId}' with the automation engine's ` + + `cancelRun('${runId}'); the submitter submits the record again.`, + ); + } + + /** + * [ADR-0162 Execution item 8] Who decided `request`: the actor of its last + * `approve` or `reject` row, or `null` (a write with no actor) where none + * names one, as for the SLA sweep's auto-decision. + */ + private async deciderOf(request: any): Promise { + try { + const rows = await this.engine.find('sys_approval_action', { + where: { request_id: request.id, action: { $in: ['approve', 'reject'] } }, + orderBy: [{ field: 'created_at', order: 'desc' }], + fields: ['id', 'actor_id'], limit: 1, context: SYSTEM_CTX, + }); + const actor = Array.isArray(rows) ? rows[0]?.actor_id : undefined; + return actor != null && String(actor) !== '' ? String(actor) : null; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 8] Keep a durable note on the approval's latest + * request on the record where a later step of it was reached and could not + * open (an empty slate under `onEmptyApprovers: 'fail'`, another request + * pending on the record, or any other failure of its opening), so that the + * judgement of the approval does not depend on how the flow routed that + * failure ({@link readCarryingRun}). A failure of the approval's first + * request leaves no note: no request of it exists. Best-effort. + */ + private async noteLaterStepNotOpened( + input: { object: string; recordId: string; nodeId: string; rootRun?: ApprovalRootRun | null }, + failure: unknown, + ): Promise { + const rootRunId = input.rootRun?.runId; + if (!rootRunId) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRunId, object_name: input.object, record_id: input.recordId }, + orderBy: [{ field: 'created_at', order: 'desc' }], + limit: 1, context: SYSTEM_CTX, + }); + const latest: any = Array.isArray(rows) ? rows[0] : undefined; + if (!latest || stampOf(latest) === undefined) return; + const now = this.clock.now().toISOString(); + const reason = String((failure as { message?: unknown } | undefined)?.message ?? failure).slice(0, 500); + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [LATER_STEP_NOT_OPENED_KEY]: { node: input.nodeId, at: now, reason } }), + }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note on the approval that a later step could not open; the run\'s own stop decides its judgement', { + object: input.object, record: input.recordId, node: input.nodeId, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 D5, Execution item 7 "The check"] Judge an approval at its first + * request, and answer the between-two-steps set the request carries + * (`between_steps_json`), or `null` where it carries none. Throws, with what + * is missing, where the approval may not open. + * + * - **Placed by its root run.** The approval is the request's root run + * (ADR-0162 item 7, slice A). A request whose run hands no root run cannot + * be placed: it is not judged and carries no set. A request of an approval + * that already has one is a later request: it is not judged again, since + * refusing it would end the approval between two steps, and it carries the + * set its approval's first request was stamped with. A request opened on + * the record since the root run started that records no root run makes + * this one unplaceable too: not judged, no set. + * - **Nothing read where nothing declares the key.** In an application where + * no object declares `closedStates`, the approval is not read. + * - **Read whole.** The flow the root run was started on and every flow a + * `subflow` or a `map` names, to any depth ({@link judgeApprovalOpening}). + * An approval that cannot be read whole is refused. + * - **Refused** where a step's mirror field is one the object closes on at a + * status of a request in flight and a condition of D5 fails, or where a + * step can act on an object that declares the key and the host runs no + * `job` service. The refusal is a `VALIDATION_FAILED`, whose sentence names + * the flow, the step, the object, the field and what is missing, in the + * run's locale where the plugin carries it ({@link openingRefusalText}). + * The node fails the run with it, which is what the submitter reads. + */ + private async judgeOpening( + input: { + object: string; recordId: string; runId: string; nodeId: string; + flowName?: string; flowKey?: string; runRoot?: boolean; + rootRun?: ApprovalRootRun | null; locale?: string; + }, + context: ExecutionContext, + ): Promise { + const rootRun = input.rootRun; + if (!rootRun?.runId) return null; + + // A later request of the same approval carries its first request's set. + let earlier: any[]; + try { + earlier = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRun.runId }, + fields: ['id', 'between_steps_json', 'created_at'], + orderBy: [{ field: 'created_at', order: 'asc' }], + limit: 1, context: SYSTEM_CTX, + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether a request is its approval\'s first; it opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + if (Array.isArray(earlier) && earlier[0]) { + const stamp = earlier[0].between_steps_json; + return typeof stamp === 'string' && stamp !== '' ? stamp : null; + } + // A request on the record since the root run started that records no root + // run: the plugin cannot tell whether it was this approval's first. + if (rootRun.startedAt) { + try { + const unplaced = await this.engine.find('sys_approval_request', { + where: { + object_name: input.object, record_id: input.recordId, root_run_id: null, + created_at: { $gte: rootRun.startedAt }, + }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(unplaced) && unplaced[0]) return null; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the record\'s earlier requests; the request opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + } + + // Nothing is read in an application where no object declares the key. + const declares = (object: string | null | undefined): boolean => { + if (!object) return false; + try { return closedValuesOf(this.engine.getSchema?.(object)) !== undefined; } catch { return false; } + }; + let appDeclares: boolean; + let listed: unknown[] | undefined; + try { listed = this.engine.registry?.getAllObjects?.(); } catch { listed = undefined; } + if (Array.isArray(listed)) appDeclares = listed.some((o) => closedValuesOf(o) !== undefined); + else appDeclares = declares(input.object) || declares(rootRun.object); + if (!appDeclares) return null; + + const judgement = await judgeApprovalOpening({ + rootFlow: await this.openingRootFlow(input, rootRun), + rootFlowName: rootRun.flowName, + rootObject: rootRun.object ?? null, + }, { + objectSchema: (name) => { try { return this.engine.getSchema?.(name); } catch { return undefined; } }, + calleeFlow: (name, callerKey) => this.openingCalleeFlow(name, callerKey), + nodeDescriptor: (type) => { + if (typeof this.automation?.getActionDescriptor !== 'function') return 'unread'; + try { return this.automation.getActionDescriptor(type); } catch { return 'unread'; } + }, + hostRunsReconciler: this.sweepClockScheduled, + }); + if (judgement.gaps.length > 0) { + const locale = input.locale ?? (context as { locale?: string } | undefined)?.locale; + this.logger?.warn?.(gapsAreAboutTheField(judgement.gaps) + ? '[approvals] an approval was refused at its first request: the record\'s object closes on its approval field and the approval cannot show it in progress (ADR-0162 D5)' + : '[approvals] an approval was refused at its first request: it can act on an object that declares closedStates, and this host runs no job service or a flow it runs could not be read (ADR-0162 D5)', { + object: input.object, record: input.recordId, run: input.runId, rootRun: rootRun.runId, + gaps: judgement.gaps.map((g) => g.kind), + }); + throw new Error(`VALIDATION_FAILED: ${openingRefusalText(judgement.gaps, { object: input.object, record: input.recordId }, locale)}`); + } + if (!judgement.touchesClosedStates) return null; + return JSON.stringify(judgement.between); + } + + /** + * [ADR-0162 Execution item 7] The flow the approval's root run was started + * on, by the key the engine files it under: the request's own run's key + * where that run is the root, else the key the root run is parked under + * (it is parked at the `subflow` or the `map` that started this run), else + * the bare name. `null` where none can be read. + */ + private async openingRootFlow( + input: { flowName?: string; flowKey?: string; runRoot?: boolean }, + rootRun: ApprovalRootRun, + ): Promise { + const automation = this.automation; + if (!automation) return null; + const byKey = (key: string | undefined): any => { + if (!key || typeof automation.getRunFlow !== 'function') return null; + try { return automation.getRunFlow({ flowName: key }); } catch { return null; } + }; + try { + let key: string | undefined = input.runRoot ? (input.flowKey ?? input.flowName) : undefined; + if (!key) { + try { key = (await automation.suspensionOf?.(rootRun.runId))?.flowName; } catch { key = undefined; } + } + const body = byKey(key) ?? (typeof automation.getFlow === 'function' ? await automation.getFlow(rootRun.flowName) : null); + if (!body || typeof body !== 'object') return null; + return { key: key ?? rootRun.flowName, body }; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 7] The flow a `subflow` or a `map` of the flow + * filed under `callerKey` names as `name`: the one flow of a name one + * package holds (or none does), and for a name two packages hold, the + * caller's own package's slot. `null` where that cannot be read, which + * makes the approval one that cannot be read whole. + */ + private async openingCalleeFlow(name: string, callerKey: string): Promise { + const automation = this.automation; + if (!automation) return null; + try { + const slots = typeof automation.getFlowSlots === 'function' ? automation.getFlowSlots(name) : []; + if (slots.length > 1) { + const pkg = this.flowPackageOf(callerKey); + if (!pkg || typeof automation.getFlowSlot !== 'function') return null; + const body = automation.getFlowSlot(pkg, name); + const key = automation.flowSlotKey?.(pkg, name) ?? name; + return body && typeof body === 'object' ? { key, body } : null; + } + const body = typeof automation.getFlow === 'function' ? await automation.getFlow(name) : null; + return body && typeof body === 'object' ? { key: name, body } : null; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 8] Whether `row` is its approval's first request on + * its record: no other request on the record names the same approval. The + * approval is the request's root run (`root_run_id`, ADR-0162 Execution item + * 7), or its own run where no root run was recorded. A later step, a later + * round of a resubmitted step and a step of a `subflow` child all share it. + * + * A read that fails answers "not the first": the refusal is then reported and + * the request stays open on an open value, where the other answer would fail + * the run between two steps on a guess. + */ + private async isFirstRequestOfApproval(row: any): Promise { + const approval = row?.root_run_id ? { root_run_id: row.root_run_id } : { flow_run_id: row?.flow_run_id }; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { object_name: row.object_name, record_id: row.record_id, ...approval }, + fields: ['id'], limit: 2, context: SYSTEM_CTX, + }); + return !(Array.isArray(rows) ? rows : []).some((r: any) => String(r?.id) !== String(row.id)); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether a request is its approval\'s first; a refused status write is reported, not refused', { + request: row?.id, error: err?.message ?? String(err), + }); + return false; + } + } + + /** + * [ADR-0162 D5] An approval's first request whose `pending` a rule or a hook + * of the app refused, on a field the object closes on: the row is voided + * with the status the platform already has for that, `cancelled`, the + * approvers' index is emptied so that nobody's inbox lists it, and its + * timeline carries the refusal. The caller then fails the run at this step + * with the refusal's own message, which is what the submitter reads; the + * record keeps the value it held. + */ + private async voidRefusedOpening(row: any, refusal: MirrorRefusal, requestOrg: string | null | undefined): Promise { + const now = this.clock.now().toISOString(); + await this.engine.update('sys_approval_request', { + id: row.id, status: 'cancelled', pending_approvers: null, pending_approver_labels: null, + completed_at: now, updated_at: now, + }, { context: SYSTEM_CTX }); + await this.syncApproverIndex(row.id, [], requestOrg ?? null, now); + await this.engine.insert('sys_approval_action', await this.actionRow(row, { + id: uid('aact'), request_id: row.id, organization_id: requestOrg ?? null, + step_name: row.current_step ?? null, step_index: 0, action: 'comment', + actor_id: null, + comment: refusedMirrorNoteText('pending', refusal.message), + created_at: now, + }), { context: SYSTEM_CTX }); + this.logger?.warn?.( + `[approvals] the approval of ${row.object_name}/${row.record_id} did not open: a rule or a hook of the app ` + + `refused its status 'pending' (${refusal.message}), so the request was voided and the run fails at this step.`, + { request: row.id, object: row.object_name, record: row.record_id, error: refusal.message }, + ); + } + + /** + * [ADR-0162 D5, Execution item 8] Report a write of the status mirror that a + * rule or a hook of the app refused, on a field the object closes on. Three + * things, each best-effort so that one failing does not hide the others: + * + * - an `error` line: the record now reads a status its approval does not + * hold, nothing else looks broken, and the fix is the app's rule or hook; + * - a line with no actor on the request's timeline, carrying the refusal's + * own message, which everyone who can read the request sees; + * - a notice to the organization's administrators, who can change the rule + * ({@link organizationAdministrators}). + */ + private async reportRefusedMirror( + object: string, + recordId: string, + field: string, + status: string, + reason: string, + about: MirrorRequestRef, + requestOrg: string | null | undefined, + ): Promise { + const request = about.request; + const requestId = String(request?.id ?? ''); + this.logger?.error?.( + `[approvals] the approval status '${status}' was NOT written to ${object}.${field} on record '${recordId}': ` + + `a validation rule, an option's visibleWhen or a hook of the app refused the write (${reason}). The object ` + + `closes on this field, so the record now reads a status its approval does not hold, and nothing else looks ` + + `broken. Change the rule or hook so that it admits the approval's status; request '${requestId}' holds the ` + + `decision, and its timeline and the organization's administrators were told.`, + undefined, + { object, record: recordId, field, value: status, request: requestId, error: reason }, + ); + const now = this.clock.now().toISOString(); + try { + // The reconciler tries a refused write again on each pass: the line is + // left once for one refusal. + if (!(await this.hasTimelineLine(requestId, refusedMirrorNoteText(status, reason)))) { + await this.engine.insert('sys_approval_action', await this.actionRow(request, { + id: uid('aact'), request_id: requestId, organization_id: requestOrg ?? null, + step_name: about.step ?? request?.current_step ?? null, step_index: 0, action: 'comment', + actor_id: null, + comment: refusedMirrorNoteText(status, reason), + created_at: now, + }), { context: SYSTEM_CTX }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note a refused status write on the request timeline', { + request: requestId, error: err?.message ?? String(err), + }); + } + try { + const admins = await this.organizationAdministrators(requestOrg); + if ('ids' in admins && admins.ids.length) { + await this.notify({ + topic: REFUSED_MIRROR_TOPIC, + organizationId: requestOrg, + audience: admins.ids, + source: { object: 'sys_approval_request', id: requestId }, + dedupKey: `approval-mirror-refused-${requestId}-${status}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalStatusMirrorRefusedTitle', body: 'approvalStatusMirrorRefusedBody', + params: { ...subject, reason }, + }), + }); + } else if ('failure' in admins) { + this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them of a refused status write', { + request: requestId, organizationId: requestOrg ?? null, error: admins.failure, + }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators of a refused status write', { + request: requestId, error: err?.message ?? String(err), + }); + } + } + + /** + * [#24577] The value a status mirror writes onto `object.field` for + * `status`, or {@link STATUS_NOT_MIRRORED} when it writes nothing. + * + * A field's declared options are its value set (the triage ruling on the + * card): the producer never writes outside them. The engine's validator does + * not hold that line for this write — it judges a `readonly` field's value + * for shape only, and the mirrored field is readonly by the spec's own advice + * — so a select that never declared `recalled` came to hold it, and an app + * whose submit gate admits only the select's own values never re-entered + * approval. The options are read from the registry the engine validates the + * same write against (`getSchema` answers `registry.getObject`). + * + * - A field with no declared value set ({@link declaredOptionValues}) and a + * status the field declares: the status, as before. + * - A transition that ABANDONS the request (a recall, the dead-run sweep), + * `abandoned` set: the record goes back to where it stood before it + * entered approval. That is the value the field held in the request's + * submit snapshot (`payload_json`, the trigger record the flow started + * from) when that is a declared value or none; else what a never-submitted + * record carries — the field's declared default, or empty. Whether the + * record re-enters approval is then the app's own gate's decision. + * - Every other transition (open, decide, send-back, the revision-limit + * auto-reject): nothing. Send-back is here, not with recall, because its + * run is still alive in the revise window (ADR-0044): a pre-approval value + * restored there re-admits the start condition ADR-0044 tells authors to + * gate on this field, and opens a parallel approval of the same record. + */ + private mirroredStatusValue( + object: string, + field: string, + status: string, + abandoned: { payloadJson: unknown } | undefined, + ): unknown { + let def: { defaultValue?: unknown } | undefined; + try { + const schema = this.engine.getSchema?.(object) as { fields?: Record } | undefined; + def = schema?.fields?.[field] as typeof def; + } catch { /* schema unavailable — no declared value set to hold the write to */ } + const declared = declaredOptionValues(def); + if (!declared || declared.includes(status)) return status; + if (!abandoned) return STATUS_NOT_MIRRORED; + const snapshot = parseJson(abandoned.payloadJson, undefined); + if (snapshot && typeof snapshot === 'object' && Object.prototype.hasOwnProperty.call(snapshot, field)) { + const held = (snapshot as Record)[field]; + if (held == null) return null; + if (holdsDeclaredValues(held, declared)) return held; + } + return holdsDeclaredValues(def?.defaultValue, declared) ? def!.defaultValue : null; + } + + /** + * [ADR-0162 D1] The values `object` declares closed on `field` + * (`closedStates[field]`), read from the registry the engine validates the + * mirror's write against, as {@link closesOnApprovalOutcome} reads them. + * Empty where the object declares none for the field, or where the schema + * cannot be read: the mirror then chooses as it did before the key. + */ + private closedValuesOf(object: string, field: string): string[] { + let closedStates: unknown; + try { + closedStates = (this.engine.getSchema?.(object) as { closedStates?: unknown } | undefined)?.closedStates; + } catch { /* schema unavailable — no closed value can be read */ } + if (!closedStates || typeof closedStates !== 'object') return []; + const closed = (closedStates as Record)[field]; + return Array.isArray(closed) ? closed.map((v) => String(v)) : []; + } + + /** + * [ADR-0162 D5, Execution item 7] What the mirror writes for a request that + * is abandoned (a recall, its override arm, the dead-run sweep) where the + * object closes on `field` on any value (`closed`). Ruling record + * 7201405662: 「平台堵住:撤回不恢复关闭值」. + * + * 1. **A closed value the approval did not write is left alone.** The field + * is read as it stands. Where it holds a closed value, the request is + * placed by its root run and the request table is asked, in one probe + * ({@link approvalWroteHeldValue}), whether a request of the same + * approval on the same record had that value as its status. Where none + * did, nothing is written. Where one did, or where it cannot tell, the + * mirror goes on to 2. + * 2. **`recalled`**, where the field declares it (or declares no value set) + * and the object does not close on it. A declared `recalled` the object + * closes on is withheld, and said so. + * 3. **The order**: the value held at submit, the field's declared + * default, empty. A closed value is passed over at each step, and so is a + * value the field does not declare (#24577). On a required field an + * empty value at submit is passed over for the default; on a field that + * is not required it is put back. + * + * Each departure from what the mirror wrote before the key is logged + * (N21): a withheld `recalled` at `warn`, since the author's closed value + * on it closes nothing through the mirror; a passed-over closed value and a + * value left alone at `info`. + */ + private async abandonedValueOnClosingField( + object: string, + recordId: string, + field: string, + closed: readonly string[], + abandoned: { payloadJson: unknown }, + about: MirrorRequestRef | undefined, + ): Promise<{ write: unknown } | { leave: true }> { + const isClosed = (v: unknown) => (Array.isArray(v) ? v : [v]).some((x) => x != null && closed.includes(String(x))); + const isEmpty = (v: unknown) => v == null || v === '' || (Array.isArray(v) && v.length === 0); + const request = about?.request; + const where = { object, record: recordId, field, request: request?.id ?? null }; + + // 1. A closed value the approval did not write is left alone. + let held: unknown; + let heldRead = false; + try { + const rows = await this.engine.find(object, { + where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX, + }); + const row = Array.isArray(rows) ? rows[0] : undefined; + if (row) { held = row[field]; heldRead = true; } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the status field of an abandoned request\'s record; the mirror goes down its order', { + ...where, error: err?.message ?? String(err), + }); + } + if (heldRead && isClosed(held)) { + const wrote = await this.approvalWroteHeldValue(request, held); + if (wrote === 'not') { + this.logger?.info?.( + `[approvals] the abandoned approval left ${object}.${field} at '${String(held)}': the object closes on that value ` + + `and no request of this approval on the record held it, so another writer put it there and the mirror writes nothing.`, + { ...where, value: held }, + ); + return { leave: true }; + } + } + + let def: { defaultValue?: unknown; required?: unknown } | undefined; + try { + const schema = this.engine.getSchema?.(object) as { fields?: Record } | undefined; + def = schema?.fields?.[field] as typeof def; + } catch { /* schema unavailable — no declared value set */ } + const declared = declaredOptionValues(def); + const usable = (v: unknown) => !declared || holdsDeclaredValues(v, declared); + const passedOver: Array<{ from: 'submit' | 'default'; value: unknown }> = []; + const passed = () => { + if (passedOver.length === 0) return; + this.logger?.info?.( + `[approvals] the abandoned approval passed over ${passedOver.map((p) => `'${String(p.value)}' (${p.from === 'submit' ? 'the value at submit' : 'the default'})`).join(' and ')} ` + + `for ${object}.${field}: the object closes on it, and an abandoned approval never writes a closed value.`, + { ...where, passedOver }, + ); + }; + + // 2. `recalled`, where the field may hold it and the object does not close on it. + const declaresRecalled = !declared || declared.includes('recalled'); + if (declaresRecalled && !closed.includes('recalled')) return { write: 'recalled' }; + if (declaresRecalled) { + this.logger?.warn?.( + `[approvals] the abandoned approval did not write 'recalled' to ${object}.${field}: the object closes on 'recalled', ` + + `and an abandoned approval never writes a closed value, so the field takes the value at submit, the default or empty. ` + + `To show a withdrawn approval on the record, remove 'recalled' from the field's closed values.`, + { ...where, value: 'recalled' }, + ); + } + + // 3. The order: the value held at submit, the declared default, empty. + const snapshot = parseJson(abandoned.payloadJson, undefined); + if (snapshot && typeof snapshot === 'object' && Object.prototype.hasOwnProperty.call(snapshot, field)) { + const atSubmit = (snapshot as Record)[field]; + if (isEmpty(atSubmit)) { + if (def?.required !== true) { passed(); return { write: null }; } + } else if (isClosed(atSubmit)) { + passedOver.push({ from: 'submit', value: atSubmit }); + } else if (usable(atSubmit)) { + passed(); + return { write: atSubmit }; + } + } + const fallback = def?.defaultValue; + if (!isEmpty(fallback)) { + if (isClosed(fallback)) passedOver.push({ from: 'default', value: fallback }); + else if (usable(fallback)) { passed(); return { write: fallback }; } + } + passed(); + return { write: null }; + } + + /** + * [ADR-0162 D5, Execution item 7] Whether the approval `request` belongs to + * wrote `held`, the closed value its record's status field holds: whether a + * request of the same approval on the same record had it as its status. + * + * - `'not'`: no such request — `held` is not a status the mirror writes + * (`pending`, `returned`, `approved`, `rejected`), or the probe found none; + * - `'wrote'`: the request itself held it (every request opens on + * `pending`, and a recall in the revise window abandons a `returned` + * one), or the probe found a request of the approval that did; + * - `'unknown'`: the request records no root run (seat ruling 7210700837: + * it goes down the order), the probe found a request that records none + * and was opened since the approval's run started, or the probe failed. + * + * The approval is the request's root run (`root_run_id`), and the record is + * its `object_name` and `record_id`: a `map` item's request on another + * record does not count. One probe of the request table, on the index + * slice A declared for it. + */ + private async approvalWroteHeldValue(request: any, held: unknown): Promise<'wrote' | 'not' | 'unknown'> { + if (typeof held !== 'string' || !MIRRORED_REQUEST_STATUSES.has(held)) return 'not'; + if (held === 'pending' || held === String(request?.status ?? '')) return 'wrote'; + const rootRunId = request?.root_run_id ? String(request.root_run_id) : ''; + if (!rootRunId) return 'unknown'; + const startedAt = request?.root_run_started_at ?? null; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { + object_name: request.object_name, + record_id: request.record_id, + status: held, + $or: [ + { root_run_id: rootRunId }, + startedAt != null ? { root_run_id: null, created_at: { $gte: startedAt } } : { root_run_id: null }, + ], + }, + fields: ['id', 'root_run_id'], limit: 1, context: SYSTEM_CTX, + }); + const found = Array.isArray(rows) ? rows[0] : undefined; + if (!found) return 'not'; + return String(found.root_run_id ?? '') === rootRunId ? 'wrote' : 'unknown'; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether an abandoned request\'s approval wrote the closed value its record holds; the mirror goes down its order', { + request: request?.id ?? null, value: held, error: err?.message ?? String(err), + }); + return 'unknown'; + } + } + + /** + * The context a named actor's status mirror writes under (see + * {@link mirrorStatusField}): `{ isSystem: true, userId, tenantId }` and + * nothing else. The organisation is the subject record's live one, read + * through {@link recordOrgResolver} — the resolver the request row was + * stamped by — and the request's own organisation for an object that has + * none (or a record that carries none), as at the stamp. ⛔ No `positions` / + * `permissions`: a carried array is kept verbatim by every `runAs:'user'` + * consumer, so an empty one would stand in for the actor's own grants. + */ + private async attributedMirrorContext( + object: string, + recordId: string, + actorId: string, + requestOrg: string | null | undefined, + ): Promise { + const column = this.recordOrgResolver.organizationFieldFor(object); + let organization: string | null = null; + if (column) { + const rows = await this.engine.find(object, { + where: { id: recordId }, fields: ['id', column], limit: 1, context: SYSTEM_CTX, + }); + organization = this.recordOrgResolver.organizationOf(object, Array.isArray(rows) ? rows[0] : undefined); + } + if (!organization && requestOrg != null && String(requestOrg) !== '') organization = String(requestOrg); + return { isSystem: true, userId: actorId, ...(organization ? { tenantId: organization } : {}) }; + } + + /** + * Re-read a business record's CURRENT state by id so approver resolution binds + * to live data at node entry, not the trigger snapshot the flow froze into + * `$record` at submit time (#3447). A `field` / `manager` approver names *who* + * decides, and an earlier node — or the approver of an earlier step — may have + * written that routing field after submit (e.g. a lead reviewer picking which + * departments co-review). Graph approvers (team / position / …) already query + * live; this brings the in-record types into line. + * + * Read under system identity: approver routing is a platform concern and the + * record is the flow's own subject, so the submitter's RLS/FLS must not narrow * it. Degrades to `fallback` (the snapshot) when the record can't be re-read — * hard-deleted between submit and node entry, or an object whose backend can't * serve a point read — warning rather than throwing so a transient miss can't @@ -5232,8 +7701,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * store can be asked for. `null` or absent records none. */ recordRun?: ApprovalRecordRun | null; + /** + * [ADR-0162 Execution item 7] The run's locale (`AutomationContext.locale`): + * the language of a refused opening's sentence, which the run's failure + * carries to the person who submitted. + */ + locale?: string; }, context: ExecutionContext, + ): Promise { + try { + return await this.openNodeRequestBody(input, context); + } catch (err) { + // [ADR-0162 Execution item 8] A later step of an approval that could not + // open leaves a note on the approval's latest request. + await this.noteLaterStepNotOpened(input, err); + throw err; + } + } + + /** {@link openNodeRequest}'s body: its docblock is this method's contract. */ + private async openNodeRequestBody( + input: Parameters[0], + context: ExecutionContext, ): Promise { if (!input.object) throw new Error('VALIDATION_FAILED: object is required'); if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required'); @@ -5248,6 +7738,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega throw new Error(`DUPLICATE_REQUEST: a pending approval already exists for ${input.object}/${input.recordId}`); } + // [ADR-0162 D5, Execution item 7] The check when an approval opens, before + // anything is written: a refused opening writes no request, mirrors + // nothing and takes no lock. It answers the between-two-steps set this + // request carries from its opening. + const betweenSteps = await this.judgeOpening(input, context); + // `organizationId` is not on the envelope — see isOverrideActor(). const ctxOrg = (context as any)?.organizationId ?? context?.tenantId ?? input.organizationId ?? null; const nowDate = this.clock.now(); @@ -5612,6 +8108,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const n = Array.isArray(prior) ? prior.length : 0; if (n > 0) configSnapshot.__round = n + 1; } catch { /* round display is best-effort */ } + // [ADR-0162 Execution item 8, ruling A3 on #37767] As the request opens, + // it keeps what the plugin can read of its approval's runs, so that a + // child run that ended before any door and was then trimmed is not + // needed again ({@link runsReadAtOpening}). + if (stampOf({ between_steps_json: betweenSteps }) !== undefined) { + const kept = await this.runsReadAtOpening({ + root_run_id: input.rootRun?.runId, record_run_id: input.recordRun?.runId, flow_run_id: input.runId, + object_name: input.object, record_id: input.recordId, + }); + if (kept) configSnapshot[RUNS_READ_KEY] = kept; + } const row: any = { id, process_name: processName, @@ -5642,6 +8149,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega root_run_id: input.rootRun?.runId ?? null, root_run_started_at: input.rootRun?.startedAt ?? null, record_run_id: input.recordRun?.runId ?? null, + // [ADR-0162 Execution item 7] The nodes that stand between two steps of + // the approval, stamped as the request opens ({@link judgeOpening}). + between_steps_json: betweenSteps, node_config_json: JSON.stringify(configSnapshot), organization_id: requestOrg, created_at: now, @@ -5649,6 +8159,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX }); await this.syncApproverIndex(id, approvers, requestOrg, now, platformSlotOpened); + // [ADR-0162 Execution item 8] A new request of the approval ends the + // passage its earlier decisions began: their marks are cleared. + await this.clearEarlierMarks(row); await this.engine.insert('sys_approval_action', await this.actionRow(row, { id: uid('aact'), request_id: id, organization_id: requestOrg, step_name: input.nodeId, step_index: 0, action: 'submit', @@ -5693,6 +8206,32 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), { context: SYSTEM_CTX }); } + // [ADR-0162 D5, Execution item 8] On a field the object closes on at + // `approved` or `rejected`, the `pending` is written here: after the row, + // which is written first, and before anyone is told of the request. At an + // approval's first request this is the one write of the mirror that takes a + // record off a closed value, and a rule or a hook of the app that refuses + // it holds: the approval does not open, the row is voided as `cancelled`, + // no lock is taken (the pending lock keys on `status: 'pending'`) and the + // run fails at this step with the refusal's own message. The other order + // could leave a decided document on `pending` with no request. At any + // later request a refusal leaves an open value on the field, and it is + // reported (`reportRefusedMirror`). Every other field is mirrored below, + // as before. + const mirrorField = input.config.approvalStatusField; + const closingMirror = !!mirrorField && this.closesOnApprovalOutcome(input.object, mirrorField); + if (closingMirror) { + const opening = await this.isFirstRequestOfApproval(row); + const refusal = await this.mirrorStatusField( + input.object, input.recordId, mirrorField!, 'pending', + row.submitter_id ?? null, requestOrg, undefined, { request: row, step: input.nodeId, opening }, + ); + if (refusal && opening) { + await this.voidRefusedOpening(row, refusal, requestOrg); + throw refusal.refused instanceof Error ? refusal.refused : new Error(refusal.message); + } + } + // OOO substitution audit + notification (#1322 M4). Each hop that rerouted // an approver away from an out-of-office user is recorded on the request's // audit trail (a system action, no human actor) and notified to both the @@ -5752,7 +8291,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // Record lock (when `lockRecord !== false`) is enforced by the beforeUpdate // hook keyed on the now-pending request; no extra write needed here. - if (input.config.approvalStatusField) { + if (input.config.approvalStatusField && !closingMirror) { // Attributed to whoever the row itself calls the submitter (#3783), so // there is exactly one answer to "who submitted this". Not the // {@link actingUserId} route: `submitterId` is server-supplied here (the @@ -6301,17 +8840,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega acceptedOutputs || (config as any).__decisionOutputs ? { ...((config as any).__decisionOutputs ?? {}), ...(acceptedOutputs ?? {}) } : undefined; + // [ADR-0162 Execution item 8] The decision leaves the mark on a request of + // an approval the check stamped, in the update that records it. await this.engine.update('sys_approval_request', { id: requestId, status: finalStatus, pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), ...(mergedOutputs ? { node_config_json: JSON.stringify({ ...config, __decisionOutputs: mergedOutputs }), } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, finalStatus, - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } const fresh = await this.readBackRequest(requestId, context); @@ -6829,6 +9371,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega submitterToldBy: 'outcome' | 'escalation', ): Promise { const result = await this.decideNode(requestId, input, context); + // [ADR-0162 Execution item 8] After the resume, the door judges the + // approval: the outcome is written only once it is over. + const judge = () => this.judgeApprovalAfterDoor( + result.request, `the ${result.decision} decision`, { requestId: String(requestId), actorId: actingUserId(context) }, + ); let resumed = false; let resumeError: string | undefined; @@ -6852,21 +9399,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // session), never off the input: the decider's segment names them, as // the decision's own audit row does. Only beside a decider. const impersonatedBy = decider ? impersonatorOf(context) : undefined; - const outcome = await this.resumeRecordedOutcome( - result.runId, requestId, `the ${result.decision} decision`, - { - branchLabel, - // #3447 P2: accepted decision outputs ride the resume envelope and - // land as `.` flow variables — a later approval node's - // `expression` approver reads them as `vars..`. - // Reserved keys are spread LAST so no output can shadow them (the - // whitelist already rejects them; this is defense in depth). - output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, - ...(decider ? { resumedBy: decider } : {}), - ...(impersonatedBy ? { impersonatedBy } : {}), - }, - result.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + result.runId, requestId, `the ${result.decision} decision`, + { + branchLabel, + // #3447 P2: accepted decision outputs ride the resume envelope and + // land as `.` flow variables — a later approval node's + // `expression` approver reads them as `vars..`. + // Reserved keys are spread LAST so no output can shadow them (the + // whitelist already rejects them; this is defense in depth). + output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, + ...(decider ? { resumedBy: decider } : {}), + ...(impersonatedBy ? { impersonatedBy } : {}), + }, + result.decision, + ); + } catch (err) { + // [ADR-0162 Execution item 8] A run that failed after the decision + // ended where it stopped: the door judges it before it reports the strand. + await judge(); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; resumeFailure = outcome.resumeFailure; @@ -6876,7 +9431,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // whether this decision ended the process or moved it to a further // approval step. A resume that strands has thrown above, so — as on the // send-back — a stranded decision tells no one. - if (result.finalized && submitterToldBy === 'outcome') { + // An approval the door abandoned told its submitter so itself. + const judgement = result.finalized ? await judge() : undefined; + if (result.finalized && submitterToldBy === 'outcome' && judgement !== 'abandoned') { await this.notifyDecisionOutcome(result.request, result.decision, input.comment, context); } @@ -7109,9 +9666,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // declare `recalled` goes back to its value at submit. await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'recalled', - actingUserId(context), org, { payloadJson: raw.payload_json }, + actingUserId(context), org, { payloadJson: raw.payload_json }, { request: raw, step: nodeId }, ); } + // [ADR-0162 Execution item 8] The recall abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); // A recall ABANDONS the request, so a run that cannot be resumed must not // fail the call — the withdrawal and the record-lock release are the point, @@ -7221,6 +9781,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } + // [ADR-0162 Execution item 8] After the resume or the cancel the recall + // made, the door judges the approval. + await this.judgeApprovalAfterDoor(raw, 'the recall'); + const fresh = await this.readBackRequest(requestId, context); return { request: fresh, @@ -7430,6 +9994,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ); return empty; } + // [ADR-0162 D5, "the hold"] After the pending requests are read, so that + // a delete in a passage ends its approval whether or not one is pending. + await this.endApprovalsOfDeletedRecord(object, record); if (pending.length === 0) return empty; const now = this.clock.now().toISOString(); @@ -7609,16 +10176,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * below its lowest `map:` link. `[runId]` alone when there is nothing to * walk (no record run, silently), or when the walk cannot be completed * (told at `warn`). + * + * `throughMap` is {@link cancelStoppedRun}'s: the chain is not cut at a + * `map:` link, so the batch and the runs above it are in it. */ private async voidedRunChain( requestId: string, runId: string, recordRunId: string | undefined, + whose = 'whose approval a record delete voided', + opts?: { throughMap?: boolean }, ): Promise { if (!recordRunId || recordRunId === runId) return [runId]; const alone = (why: string, error?: unknown): string[] => { this.logger?.warn?.( - '[approvals] could not read the runs above a run whose approval a record delete voided — only that run ' + `[approvals] could not read the runs above a run ${whose} — only that run ` + 'is cancelled, and a run above it may stay parked', { request: requestId, run: runId, recordRun: recordRunId, why, ...(error ? { error: (error as any)?.message ?? String(error) } : {}) }, ); @@ -7635,7 +10207,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const correlation: string = parked?.correlation ?? ''; if (correlation.startsWith('map:')) { // A batch stays a batch: the chain starts again below it. - chain.length = 0; + if (!opts?.throughMap) chain.length = 0; current = correlation.slice('map:'.length) || undefined; } else if (correlation.startsWith('subflow:')) { current = correlation.slice('subflow:'.length) || undefined; @@ -7720,29 +10292,40 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), { context: SYSTEM_CTX }); await this.engine.update('sys_approval_request', { id: requestId, status: 'rejected', pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + // [ADR-0162 Execution item 8] A decision, so it leaves the mark. + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'rejected', - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the auto-rejection', - { - branchLabel: APPROVAL_BRANCH_LABELS.reject, - output: { decision: 'reject', autoRejected: true, requestId }, - }, - 'reject', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the auto-rejection', + { + branchLabel: APPROVAL_BRANCH_LABELS.reject, + output: { decision: 'reject', autoRejected: true, requestId }, + }, + 'reject', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } - if (raw.submitter_id) { + // [ADR-0162 Execution item 8] The auto-rejection is a decision: the door judges the approval. + // An abandoned approval has told its submitter already, on its own topic. + const judged = await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + if (raw.submitter_id && judged !== 'abandoned') { await this.notify({ topic: 'approval.returned', organizationId: raw.organization_id, @@ -7767,24 +10350,32 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (config.approvalStatusField) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'returned', - actingUserId(context), org, + actingUserId(context), org, undefined, { request: raw, step: nodeId }, ); } let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the send-back', - { - branchLabel: APPROVAL_BRANCH_LABELS.revise, - output: { decision: 'revise', requestId }, - }, - 'revise', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the send-back', + { + branchLabel: APPROVAL_BRANCH_LABELS.revise, + output: { decision: 'revise', requestId }, + }, + 'revise', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the send-back'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the send-back. + await this.judgeApprovalAfterDoor(raw, 'the send-back'); if (raw.submitter_id) { // [#24978] The approver's own words, when they wrote some, are the body @@ -7873,17 +10464,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the resubmit', - { - branchLabel: APPROVAL_BRANCH_LABELS.resubmit, - output: { resubmitted: true, requestId }, - }, - 'resubmit', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the resubmit', + { + branchLabel: APPROVAL_BRANCH_LABELS.resubmit, + output: { resubmitted: true, requestId }, + }, + 'resubmit', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the resubmission. + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); const fresh = await this.readBackRequest(requestId, context); return { request: fresh, runId, resumed, ...(resumeError ? { resumeError } : {}) }; @@ -9031,6 +11630,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega for (const raw of rows) { const runId = raw?.flow_run_id ? String(raw.flow_run_id) : ''; if (!runId) continue; // not node-driven — no run was ever supposed to move + // [ADR-0162 Execution item 8] A decided request of an approval the check + // stamped is the door's and the reconciler's ({@link reconcileMarkedApprovals}), + // which judge it and end its hold: this report does not name it as + // well. A returned one (a send-back sets no mark, and no judgement + // places a returned request) is reported as before. + if (stampOf(raw) !== undefined && (raw.status === 'approved' || raw.status === 'rejected')) continue; let suspended: boolean; try { @@ -9616,6 +12221,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // next round. Same guard `recall`-in-revise-window and `resubmit` already // use, for the same reason. await this.assertLatestForRun(raw); + await this.refuseAbandonedContinuation(raw, requestId); // The signal, before the store is asked anything — a request this verb // cannot serve is refused without a suspension read. @@ -9694,21 +12300,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // `RESUME_IN_PROGRESS` tolerance, the same stranded envelope with the // engine's own `repairable` discriminator, and the same re-journalling — // so a continuation that strands AGAIN is repairable exactly like the first. - const outcome = await this.resumeRecordedOutcome( - runId, requestId, signal.what, - { - branchLabel: signal.branchLabel, output: signal.output, - // The journalled decider (ruling A): the replayed nodes after the - // decision run as the person who decided, not as the run's trigger. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), - // The journalled impersonator beside that decider: the replayed - // segment is stamped exactly as the decision's own resume would have. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy - && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() - ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), - }, - signal.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, signal.what, + { + branchLabel: signal.branchLabel, output: signal.output, + // The journalled decider (ruling A): the replayed nodes after the + // decision run as the person who decided, not as the run's trigger. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), + // The journalled impersonator beside that decider: the replayed + // segment is stamped exactly as the decision's own resume would have. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy + && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() + ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), + }, + signal.decision, + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); + throw err; + } + // [ADR-0162 Execution item 8] The door judges the approval after the continuation. + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); return { resumed: outcome.resumed, @@ -9720,6 +12334,238 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; } + /** + * [ADR-0162 D5, Execution item 8] The reconciler: judge every approval whose + * mark no door cleared. For an approval on an object that declares + * `closedStates` it takes the place of {@link inspectStrandedRequests}, + * which skips the marked requests the check stamped. It rides the sweep + * clock. + * + * One pass reads two windows of at most `limit` (default 200) marked + * requests: the oldest marks, and the next page of a walk over every marked + * request by id, so that one pass is bounded and marks that stay cannot + * keep newer ones from being read. It judges each approval among them + * once, as the door would have ({@link judgeApprovalAfterDoor}): it is + * finished and its outcome is written in the name of the request's + * recorded decider ({@link deciderOf}), or it ended between two steps and + * is abandoned, or, where nothing was held back, the mark is cleared and + * nothing is written. It places what the door does not see: a run that was + * cancelled, a parent run that is gone. Once every mark of an approval has + * stood past {@link RECONCILER_AGE_BOUND_MS}, it also places a run that two + * passes in a row read in the same of these states, the first of which + * may be a pass within the bound or a door (rulings A3 and B2 on #37767; + * S14 of delta review 7269135624, {@link stoodState}): a run that reports + * paused while its pause is gone, a run parked at a `subflow` or a `map` + * whose child run has ended or has no row (an item run of a `map` that + * carries another record included, once it is in a terminal status), and, + * as one rule, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}), a tree of more runs than one + * judgement reads once a judgement keeps no run the approval had not kept + * ({@link MAX_RUNS_READ_PER_APPROVAL}), and the latest request's own run + * still parked at the step its decision was recorded on (at whatever depth + * below the run that carries the record), each of which has stopped at the + * step last decided. Where a step can follow it, the approval is abandoned (and + * a run still parked there is cancelled, with the runs that wait on it); + * where none can, the outcome is written and, once it has landed, the + * administrators are told that the flow could not be seen through to its + * end after its last step. + * + * What each judgement reads of the runs is kept on the approval's latest + * request ({@link RunsRead}), so a pass reads on from where the last one + * stopped: a run is not read again only once it and every run below it + * were read to an end. + * + * A refused outcome or put-back leaves the marks, so the next pass tries it + * again; the mirror's notice to the administrators is keyed per request and + * status, so it is sent once. For a record that was deleted, the marks of + * its approval are cleared and nothing is written: no retry and no notice. + * An approval it cannot tell about keeps its marks for the next pass. + * Each of the states it holds within the age bound is placed past it, + * once a reading of that state is kept and the next one reads the same. + * That has an end where the kept write lands; an approval whose reading + * is never kept, and that kept no such state before, is held with no end + * ({@link keepRunsRead}). What also stays cannot tell at any age is a run + * that cannot be read (a store that does not answer, a run that reports a + * status the plugin does not place or that another process is advancing): + * it is read again on the next pass. + * + * Best-effort: one approval's failure costs only that approval. + */ + async reconcileMarkedApprovals(options?: { limit?: number }): Promise<{ + scanned: number; + judged: Partial>; + deletedRecords: number; + }> { + const judged: Partial> = {}; + let deletedRecords = 0; + let rows: any[]; + // S2 of 7255916895: two windows of at most `limit` rows each, as the + // stranded-request report reads (#37808). The OLDEST marks, so that an + // approval left waiting longest is judged first; and the next page of a + // WALK over every marked request by id, resumed where the previous pass + // stopped and restarted once it runs out, so that marks which stay + // (an approval in progress, or one that cannot be told yet) cannot hold + // the head of every scan and keep the newer ones from being read. + const limit = options?.limit ?? 200; + const marked = { $null: false }; + try { + const oldest: any[] = (await this.engine.find('sys_approval_request', { + where: { unjudged_since: marked }, + orderBy: [{ field: 'unjudged_since', order: 'asc' }, { field: 'id', order: 'asc' }], + limit, context: SYSTEM_CTX, + })) ?? []; + const cursor = this.reconcileScanCursor; + const walked: any[] = (await this.engine.find('sys_approval_request', { + where: cursor ? { unjudged_since: marked, id: { $gt: cursor } } : { unjudged_since: marked }, + orderBy: [{ field: 'id', order: 'asc' }], + limit, context: SYSTEM_CTX, + })) ?? []; + this.reconcileScanCursor = walked.length < limit ? null : String(walked[walked.length - 1].id); + const inOldest = new Set(oldest.map((r) => String(r?.id))); + rows = [...oldest, ...walked.filter((r) => !inOldest.has(String(r?.id)))]; + } catch (err: any) { + this.logger?.warn?.('[approvals] the reconciler could not list the marked requests', { + error: err?.message ?? String(err), + }); + return { scanned: 0, judged, deletedRecords }; + } + + const seen = new Set(); + for (const raw of rows) { + if (!isMarked(raw)) continue; + const key = raw?.root_run_id + ? `${String(raw.root_run_id)}\u0000${String(raw.object_name)}\u0000${String(raw.record_id)}` + : `request\u0000${String(raw?.id)}`; + if (seen.has(key)) continue; + seen.add(key); + try { + if (await this.recordIsGone(raw)) { + await this.endApprovalOfDeletedRecord(raw); + deletedRecords++; + this.logger?.info?.( + `[approvals] the reconciler cleared the marks of the approval of ${String(raw.object_name)}/${String(raw.record_id)}: ` + + 'the record was deleted, so nothing is written.', + { request: raw.id }, + ); + continue; + } + const answer = await this.judgeApprovalAfterDoor(raw, 'the reconciler', undefined, { ageBoundMs: RECONCILER_AGE_BOUND_MS }); + judged[answer] = (judged[answer] ?? 0) + 1; + // A mark on a request that carries no stamp or no root run can never + // be judged; left, it would hold its place at the head of every scan. + if (answer === 'unstamped') await this.clearMarks([raw]); + } catch (err: any) { + this.logger?.warn?.('[approvals] the reconciler could not judge an approval; its marks stand for the next pass', { + request: raw?.id, error: err?.message ?? String(err), + }); + } + } + return { scanned: rows.length, judged, deletedRecords }; + } + + /** + * [ADR-0162 Execution item 8] Whether `row`'s record was deleted: a read of + * it answers no row. A read that fails is not an answer, and the approval is + * judged as any other. + */ + private async recordIsGone(row: any): Promise { + const object = String(row?.object_name ?? ''); + const recordId = String(row?.record_id ?? ''); + if (!object || !recordId) return false; + try { + const found = await this.engine.find(object, { + where: { id: recordId }, fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + return Array.isArray(found) && found.length === 0; + } catch { + return false; + } + } + + /** + * [ADR-0162 D5 "the hold", Execution item 8] End the approval `row` belongs + * to, whose record was deleted: the approval is marked abandoned on its + * latest request on the record, its marks are cleared and nothing is + * written, so that no mark of a deleted record stands for good, holds + * nothing, and leaves the reconciler nothing to try again or to notify for. + * The decisions already made stay on their requests. A request already + * marked abandoned is not stamped again. + */ + private async endApprovalOfDeletedRecord(row: any): Promise { + if (!row?.root_run_id) { + await this.clearMarks([row]); + return; + } + const found = await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'created_at', 'unjudged_since', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + }); + const rows: any[] = Array.isArray(found) && found.length > 0 ? found : [row]; + const at = (r: any): number => { + const t = new Date(r?.created_at ?? '').getTime(); + return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY; + }; + const latest = rows.reduce((best, r) => (best === undefined || at(r) > at(best) ? r : best), undefined); + const abandoned = rows.some((r) => parseJson>(r?.node_config_json, {})[ABANDONED_KEY] !== undefined); + if (latest && !abandoned) { + const now = this.clock.now().toISOString(); + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [ABANDONED_KEY]: { at: now, reason: 'the record was deleted.' } }), + }, { context: SYSTEM_CTX }); + } + await this.clearMarks(rows); + } + + /** + * [ADR-0162 D5 "the hold", Execution item 8] A caller's delete lands in a + * passage, as it lands while a request is pending, and ends the approval of + * the deleted record ({@link endApprovalOfDeletedRecord}), once for each + * approval whose marks stand on it. Best-effort, like the rest of the + * record-delete void: a mark this cannot clear is the reconciler's, which + * ends the approval the same way. + */ + private async endApprovalsOfDeletedRecord(object: string, record: string): Promise { + let marked: any[]; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { object_name: object, record_id: record, unjudged_since: { $null: false } }, + limit: RECORD_DELETE_CANCEL_LIMIT, context: SYSTEM_CTX, + }); + marked = Array.isArray(rows) ? rows : []; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the marks on a deleted record; the reconciler ends its approval', { + object, record, error: err?.message ?? String(err), + }); + return []; + } + const ended: string[] = []; + const seen = new Set(); + for (const raw of marked) { + if (!isMarked(raw)) continue; + const key = raw?.root_run_id ? String(raw.root_run_id) : `request\u0000${String(raw?.id)}`; + if (seen.has(key)) continue; + seen.add(key); + try { + await this.endApprovalOfDeletedRecord(raw); + ended.push(String(raw.id)); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not end the approval of a record deleted between two of its steps; the reconciler ends it', { + object, record, request: raw?.id, error: err?.message ?? String(err), + }); + } + } + if (ended.length > 0) { + this.logger?.info?.( + `[approvals] the record ${object}/${record} was deleted between two steps of its approval: the approval was ` + + 'marked abandoned and its marks cleared; nothing is written.', + { object, record, requests: ended }, + ); + } + return ended; + } + async releaseDeadRunRequests(): Promise<{ scanned: number; released: number }> { // No liveness oracle → no basis to declare anything dead. if (typeof this.automation?.getRun !== 'function') return { scanned: 0, released: 0 }; @@ -9809,9 +12655,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // options do not declare `recalled` goes back to its value at submit. await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'recalled', null, org, - { payloadJson: raw.payload_json }, + { payloadJson: raw.payload_json }, { request: raw, step: raw.current_step ?? null }, ); } + // [ADR-0162 Execution item 8] The sweep abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); this.logger?.warn?.('[approvals] released a record held by a dead approval run', { request: raw.id, run: runId, runStatus, object: raw.object_name, record: raw.record_id, diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index c757c0d7beb..0995a3117aa 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -536,6 +536,10 @@ export class ApprovalsServicePlugin implements Plugin { // that really happened), so it rides the same clock purely to make // the finding surface without an operator knowing to go looking. svc.inspectStrandedRequests(), + // [ADR-0162 Execution item 8] The reconciler: judges every approval + // whose mark no door cleared, and ends its hold. It takes the + // place of the report above for the requests the check stamped. + svc.reconcileMarkedApprovals(), ]); for (const r of results) { if (r.status === 'rejected') { @@ -548,6 +552,9 @@ export class ApprovalsServicePlugin implements Plugin { await jobs.schedule(ESCALATION_JOB_NAME, { type: 'interval', intervalMs }, sweep); this.jobService = jobs; this.escalationJobScheduled = true; + // [ADR-0162 Execution item 7] The sweeps run here, so an approval on an + // object that declares `closedStates` may open on this host. + svc.noteSweepClockScheduled(); void sweep().catch((err: any) => { ctx.logger.warn?.('[approvals] boot sweep failed', { error: err?.message }); }); diff --git a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts index 75501d513b6..2aa9c3663b9 100644 --- a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts +++ b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts @@ -168,7 +168,7 @@ const SLOT_COLUMNS = new Set(['approver', 'acted_as', 'pending_approvers']); /** The person column of `sys_approval_action` (#21411). */ const PERSON_COLUMN = 'actor_id'; -type PersonRole = 'caller-user-id' | 'display' | 'migration'; +type PersonRole = 'caller-user-id' | 'display' | 'migration' | 'attribution'; /** * Every read of `actor_id` in this package, keyed ` · String(pending?.record_id ?? ''))); } +// ── The hold through a passage (ADR-0162 D5 "the hold", Execution item 8) ── +// +// A passage is the time from a step's decision until the next request of the +// approval opens on the record, or until the approval is over. No request is +// pending in it, so the three pending reads above see nothing. On an object +// that declares `closedStates` the write side also reads the requests that +// carry the mark (`unjudged_since`): a decision of an approval the check +// stamped, whose sequel nobody has judged yet. Such a request holds its record +// and the record's direct `master_detail` lines as a pending request under a +// locking node does, with the passes D5 gives the hold: +// +// - a system context, and a write that carries only the mirror field (the +// record lock's own caller-level passes, unchanged); +// - a write that carries a run of the approval: its root run is the one the +// request records (`flowRootRunId`, ADR-0162 Execution item 7), or it is +// one of the runs the request names; +// - the revise window: the hold stands only while the marked request is the +// approval's latest on the record, so a later returned request (its revise +// window), a later pending one (the pending lock's own rules) or an +// approval marked abandoned ends it, also where a mark was left behind; +// - the record's own delete, which this `beforeUpdate` guard never sees. +// +// A passage does not ask the node's `lockRecord`: the hold is the promise of +// `closedStates`, not a node's choice. The approvals-family read +// (`getRecordLock`, {@link recordHeldByLockingApproval} and its siblings) is +// not touched and answers for a pending request only, as published. + +/** The key the approval's judgement leaves on a request's snapshot when it abandons the approval. */ +export const ABANDONED_SNAPSHOT_KEY = '__abandoned'; + +/** Whether `row` carries the mark: it was decided, and what follows is not judged yet. */ +function carriesMark(row: any): boolean { + return row?.unjudged_since != null && row.unjudged_since !== ''; +} + +/** Whether `row`'s snapshot says its approval was abandoned. */ +function snapshotAbandoned(row: any): boolean { + return parseJson>(row?.node_config_json, {})[ABANDONED_SNAPSHOT_KEY] !== undefined; +} + +/** + * Whether `objectName` declares `closedStates` with at least one closed value, + * read from the registry the engine validates writes against. A registry that + * cannot answer reads as "declares none", the same degradation the pending + * lock makes for bookkeeping it cannot read: this guard is global over every + * object. + */ +function declaresClosedStates(engine: Pick, objectName: string): boolean { + let closed: unknown; + try { + closed = engine.getSchema?.(objectName)?.closedStates; + } catch { + return false; + } + if (!closed || typeof closed !== 'object' || Array.isArray(closed)) return false; + return Object.values(closed as Record).some((v) => Array.isArray(v) && v.length > 0); +} + +/** + * The marked requests on `recordIds` of `objectName` (or on any record of it, + * for `null`), where the object declares `closedStates`. A read that fails + * answers none, like {@link pendingRequestsForRecords}. + */ +async function passageRequestsFor( + engine: Pick, + objectName: string, + recordIds: ReadonlyArray | null, +): Promise { + if (isApprovalBookkeepingObject(objectName) || !declaresClosedStates(engine, objectName)) return []; + if (recordIds !== null && recordIds.length === 0) return []; + const where: Record = { object_name: objectName, unjudged_since: { $null: false } }; + if (recordIds !== null) { + where.record_id = recordIds.length === 1 ? String(recordIds[0]) : { $in: recordIds.map(String) }; + } + try { + const rows = await engine.find('sys_approval_request', { + where, limit: PENDING_LOCK_LIMIT + 1, context: { ...SYSTEM_CTX }, + }); + return Array.isArray(rows) ? rows : []; + } catch { + return []; + } +} + +/** The runs a write carries, as the engine stamped them on its provenance. */ +interface WriterRuns { + /** The run that makes the write (`flowRunId`). */ + run?: string; + /** The root run of that run's tree (`flowRootRunId`). */ + root?: string; +} + +function writerRunsOf(ctx: any): WriterRuns { + const provenance = ctx?.provenance as { flowRunId?: unknown; flowRootRunId?: unknown } | undefined; + const run = typeof provenance?.flowRunId === 'string' && provenance.flowRunId ? provenance.flowRunId : undefined; + const root = run && typeof provenance?.flowRootRunId === 'string' && provenance.flowRootRunId + ? provenance.flowRootRunId + : undefined; + return { ...(run ? { run } : {}), ...(root ? { root } : {}) }; +} + +/** + * Whether the write is made by a run of the approval `marked` belongs to: its + * tree's root run is the one the request records, or the run is one the + * request names (the run that opened it, the root run, the run that carries + * its record). + */ +function writesAsApprovalRun(marked: any, writer: WriterRuns): boolean { + if (!writer.run) return false; + const root = marked?.root_run_id ? String(marked.root_run_id) : ''; + if (root && writer.root === root) return true; + return [marked?.flow_run_id, marked?.root_run_id, marked?.record_run_id] + .some((id) => id != null && id !== '' && String(id) === writer.run); +} + +/** + * Whether `marked`'s approval is still in the passage its decision began: the + * request is the approval's latest on its record, carries the mark, and the + * approval was not abandoned. A read that fails holds: a mark is known to + * stand. + */ +async function approvalInPassage(engine: Pick, marked: any): Promise { + if (!carriesMark(marked) || snapshotAbandoned(marked)) return false; + if (!marked?.root_run_id) return true; + let rows: any[]; + try { + const found = await engine.find('sys_approval_request', { + where: { root_run_id: marked.root_run_id, object_name: marked.object_name, record_id: marked.record_id }, + fields: ['id', 'status', 'created_at', 'unjudged_since', 'node_config_json'], + limit: 500, context: { ...SYSTEM_CTX }, + }); + rows = Array.isArray(found) ? found : []; + } catch { + return true; + } + if (rows.some(snapshotAbandoned)) return false; + const at = (r: any): number => { + const t = new Date(r?.created_at ?? '').getTime(); + return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY; + }; + const latest = rows.reduce((best, r) => (best === undefined || at(r) > at(best) ? r : best), undefined); + if (!latest) return true; + // Two requests opened in the same instant: one that is not marked (pending + // or returned) is the newer state of the approval. + const tied = rows.filter((r) => at(r) === at(latest)); + return tied.every(carriesMark); +} + +/** + * The hold's judgement of one marked request against one write: `true` where + * the write is refused. `changedFields` is the update's changed fields for the + * record itself, where a write that carries only the mirror field passes; a + * line write passes no field. + */ +async function passageHoldsAgainst( + engine: Pick, + marked: any, + writer: WriterRuns, + changedFields?: readonly string[], +): Promise { + if (writesAsApprovalRun(marked, writer)) return false; + if (changedFields) { + const mirror = parseJson(marked?.node_config_json, {})?.approvalStatusField; + if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) return false; + } + return approvalInPassage(engine, marked); +} + /** * Narrow `candidates` (pending requests) to the ones whose record the caller's * predicate actually matches — asked of the engine as an intersection, so the @@ -721,7 +889,10 @@ async function gatingRequests( objectName: string, ): Promise { const byId = asIdList(ctx?.input?.id); - if (byId) return pendingRequestsForRecords(engine, objectName, byId); + if (byId) { + const pending = await pendingRequestsForRecords(engine, objectName, byId); + return withPassage(pending, await passageRequestsFor(engine, objectName, byId)); + } // Predicate write. `where` is canonical here: the engine folds the `filter` // alias into it before hooks run (PD #12 — no consumer-side `?? filter`). @@ -732,10 +903,14 @@ async function gatingRequests( : null; const namedIds = whereObj ? asIdList(whereObj.id) : null; - const candidates = namedIds + const pending = namedIds ? await pendingRequestsForRecords(engine, objectName, namedIds) : await pendingRequestsForObject(engine, objectName); - if (candidates === null) return []; // bookkeeping unreadable — see the note above + // [ADR-0162 D5, "the hold"] The marked requests of a passage, on an object + // that declares `closedStates`, are candidates beside the pending ones. + const passage = await passageRequestsFor(engine, objectName, namedIds); + if (pending === null && passage.length === 0) return []; // bookkeeping unreadable — see the note above + const candidates = withPassage(pending ?? [], passage); if (candidates.length === 0) return []; // nothing locked in reach if (candidates.length > PENDING_LOCK_LIMIT) { lockedError( @@ -750,6 +925,13 @@ async function gatingRequests( return narrowToMatchedRecords(engine, objectName, rawWhere, candidates); } +/** `pending` and then the marked requests of `passage` that are not among them. */ +function withPassage(pending: any[], passage: any[]): any[] { + if (passage.length === 0) return pending; + const seen = new Set(pending.map((r) => String(r?.id ?? ''))); + return [...pending, ...passage.filter((r) => !seen.has(String(r?.id ?? '')))]; +} + /** * Bind the global record-lock hook. Caller is responsible for calling * {@link unbindAllHooks} first if re-binding. @@ -816,19 +998,26 @@ export function bindApprovalLockHook( // session, and that shape is the one that used to die on its own lock // (#3712). const writerRun = (ctx?.provenance as any)?.flowRunId; + const writer = writerRunsOf(ctx); // Per-row verdict: the write is refused as soon as ONE touched record is // locked against it. Each request carries its own snapshotted policy, so a // multi-row write spanning two approvals is judged by each of them. for (const pending of gating) { - if (writerRun && pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id)) continue; - - const config = parseJson(pending?.node_config_json, {}); - if (!nodeConfigLocksRecord(config)) continue; - - // Allow when every changed field is the approval status mirror. - const mirror = config?.approvalStatusField; - if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) continue; + if (pending?.status !== 'pending') { + // [ADR-0162 D5, "the hold"] A marked request of a passage: held + // whatever its node's `lockRecord`, with the hold's own passes. + if (!(await passageHoldsAgainst(engine, pending, writer, changedFields))) continue; + } else { + if (writerRun && pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id)) continue; + + const config = parseJson(pending?.node_config_json, {}); + if (!nodeConfigLocksRecord(config)) continue; + + // Allow when every changed field is the approval status mirror. + const mirror = config?.approvalStatusField; + if (typeof mirror === 'string' && mirror && changedFields.every((f) => f === mirror)) continue; + } // ── The one END-USER sentence of the four (#18153) ───────────── // See the module docstring. The id and the API name are not deleted — @@ -872,7 +1061,9 @@ export function bindApprovalLockHook( logger?.info?.( `[approvals] update refused RECORD_LOCKED: record '${recordId}' of '${object}' ` + - `is held by pending approval request '${String(pending?.id ?? '')}'`, + (pending?.status === 'pending' + ? `is held by pending approval request '${String(pending?.id ?? '')}'` + : `is held between two steps of its approval, after the decision of request '${String(pending?.id ?? '')}'`), ); const sentence = recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate); lockedError(sentence, sentence); @@ -1134,6 +1325,14 @@ export function bindDetailRowLockHook( const writerRun = (ctx?.provenance as any)?.flowRunId; const exempt = (pending: any) => !!writerRun && !!pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id); + // [ADR-0162 D5, "the hold"] The marked requests of a passage that hold a + // master against this write: a line write carries no mirror field. + const writer = writerRunsOf(ctx); + const holdingInPassage = async (marked: readonly any[]): Promise => { + const out: any[] = []; + for (const m of marked) if (await passageHoldsAgainst(engine, m, writer)) out.push(m); + return out; + }; // The end-user sentence naming the MASTER object (the record lock's own). const sentenceFor = (master: string): string => { @@ -1152,7 +1351,10 @@ export function bindDetailRowLockHook( if (unresolved) { for (const e of edges) { const held = (await pendingRequestsForObject(engine, e.master)) ?? []; - const locking = held.filter((p) => nodeConfigLocksRecord(parseJson(p?.node_config_json, {})) && !exempt(p)); + const locking = [ + ...held.filter((p) => nodeConfigLocksRecord(parseJson(p?.node_config_json, {})) && !exempt(p)), + ...await holdingInPassage(await passageRequestsFor(engine, e.master, null)), + ]; if (locking.length > 0) { lockedError( `cannot determine which '${e.master}' record a ${event} on its detail object '${object}' falls under, ` + @@ -1164,11 +1366,16 @@ export function bindDetailRowLockHook( } for (const { master, id } of touched) { - const locking = (await lockingRequestsForRecords(engine, master, [id])).filter((p) => !exempt(p)); + const locking = [ + ...(await lockingRequestsForRecords(engine, master, [id])).filter((p) => !exempt(p)), + ...await holdingInPassage(await passageRequestsFor(engine, master, [id])), + ]; if (locking.length === 0) continue; logger?.info?.( `[approvals] ${event} on detail object '${object}' refused RECORD_LOCKED: its master '${master}' ` + - `record '${id}' is held by pending approval request '${String(locking[0]?.id ?? '')}'`, + (locking[0]?.status === 'pending' + ? `record '${id}' is held by pending approval request '${String(locking[0]?.id ?? '')}'` + : `record '${id}' is held between two steps of its approval, after the decision of request '${String(locking[0]?.id ?? '')}'`), ); const sentence = sentenceFor(master); lockedError(sentence, sentence); diff --git a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts new file mode 100644 index 00000000000..b98b6ed217b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts @@ -0,0 +1,569 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7, "The mirror"] An abandoned approval never + * writes a closed value — ruling record 7201405662, 「平台堵住:撤回不恢复关闭值」. + * + * On every transition that abandons a request, where the object's + * `closedStates` lists any value for the mirror field, the mirror: + * - writes `recalled` where the field declares it and the object does not + * close on it; + * - otherwise goes down the order: the value held at submit, the field's + * declared default, empty — passing over a closed value at each step, and + * on a required field an empty value at submit for the default; + * - leaves alone a closed value the approval did not write, judged by one + * probe of the request table on the request's root run and record; where + * it cannot tell (no root run, or a request with none opened since the + * approval's run started), it goes down the order. + * + * The writers that abandon a request are counted by transition (N20): the + * submitter's recall of a pending request, the submitter's recall in the + * revise window, the override arm of `recall` taken by an administrator and + * by a system context, and the dead-run sweep. Each test records the value + * the field keeps. + * + * Driven on the real data engine (ObjectQL, its validator, SQLite through + * `SqlDriver`, the plugin's own objects synced) and the real automation + * engine with the approval node, the `request-root-run` harness. "Another + * writer" is a system write of the record while the request is pending. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { registerApprovalNode } from './approval-node.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; +const ADMIN = { userId: 'u_root', posture: 'PLATFORM_ADMIN', positions: [], permissions: [] } as any; +const SUBMITTER = 'u_sub'; +const ORG = 'org_default'; +const silentBase = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }; +const silent: any = { ...silentBase, child() { return silent; } }; + +/** Records every level, so a line the mirror owes (N21) is measurable. */ +function recordingLogger() { + const lines: Array<{ level: string; msg: string; meta?: any }> = []; + const mk = (level: string) => (msg: unknown, ...rest: unknown[]) => { + lines.push({ level, msg: String(msg), meta: rest.find((r) => r && typeof r === 'object') }); + }; + const self: any = { lines, info: mk('info'), warn: mk('warn'), error: mk('error'), debug: mk('debug'), child() { return self; } }; + return self; +} + +const STATUSES = ['draft', 'pending', 'approved', 'rejected', 'returned']; +const option = (value: string) => ({ label: value, value }); +const text = (name: string) => ({ name, label: name, type: 'text' as const }); + +/** An object whose `approval_status` select is shaped by `field`, closing on `closed` (none: no `closedStates`). */ +function doc(name: string, field: Record, closed?: string[], values: string[] = STATUSES) { + return { + name, label: name, + fields: { + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, + name: text('name'), + approval_status: { name: 'approval_status', label: 'Status', type: 'select' as const, options: values.map(option), ...field }, + }, + ...(closed ? { closedStates: { approval_status: closed } } : {}), + }; +} + +const OBJECTS = [ + doc('doc_main', { defaultValue: 'draft' }, ['approved']), + doc('doc_open_recalled', { defaultValue: 'draft' }, ['approved'], [...STATUSES, 'recalled']), + doc('doc_closed_recalled', { defaultValue: 'draft' }, ['approved', 'recalled'], [...STATUSES, 'recalled']), + doc('doc_default_closed', { defaultValue: 'approved' }, ['approved']), + doc('doc_no_default', {}, ['approved']), + doc('doc_required', { defaultValue: 'draft', required: true }, ['approved']), + doc('doc_own_values', { defaultValue: 'draft' }, ['paid'], [...STATUSES, 'paid']), + doc('doc_paid', { defaultValue: 'draft' }, ['approved', 'paid'], [...STATUSES, 'paid']), + doc('doc_control', { defaultValue: 'draft' }), + // A field that cannot show `pending`: an approval not judged at its opening, + // where an earlier step's outcome stays on the field while a later step waits. + doc('doc_no_pending', { defaultValue: 'draft' }, ['approved'], STATUSES.filter((v) => v !== 'pending')), + // N17: an empty put-back on each kind of required field, no default. + doc('doc_req_editable', { required: true }, ['approved']), + doc('doc_req_readonly', { required: true, readonly: true }, ['approved']), + doc('doc_req_system', { required: true, system: true }, ['approved']), + doc('doc_req_when_shown', { required: true, visibleWhen: 'has(record.name) && record.name != null' }, ['approved']), +]; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); +/** One step with a revise window (ADR-0044). */ +const ONE = { + name: 'one', label: 'One step', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('review', 'u_mgr'), + { id: 'wait_revision', type: APPROVAL_REVISE_NODE_TYPE, label: 'Awaiting revision' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + { id: 'e4', source: 'review', target: 'wait_revision', label: 'revise' }, + { id: 'e5', source: 'wait_revision', target: 'review', label: 'resubmit', type: 'back' }, + ], +}; +const chain = (name: string, nodes: any[]) => ({ + name, label: name, type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, ...nodes, { id: 'end', type: 'end', label: 'End' }], + edges: [ + { id: 'cstart', source: 'start', target: nodes[0].id }, + ...nodes.flatMap((n, i) => { + const next = nodes[i + 1]?.id ?? 'end'; + return n.type === 'approval' + ? [{ id: `c${i}a`, source: n.id, target: next, label: 'approve' }, { id: `c${i}r`, source: n.id, target: 'end', label: 'reject' }] + : [{ id: `c${i}`, source: n.id, target: next }]; + }), + ], +}); +/** Two steps in one run. */ +const TWO = chain('two', [step('first', 'u_mgr'), step('second', 'u_exec')]); +/** The earlier step in a `subflow` child, the abandoned one in the parent. */ +const CHILD_FIRST_BODY = chain('child_first_body', [step('first', 'u_mgr')]); +const CHILD_FIRST = chain('child_first', [{ id: 'sub', type: 'subflow', label: 'First, in a child', config: { flowName: 'child_first_body' } }, step('second', 'u_exec')]); +/** The earlier step in the parent, the abandoned one in a `subflow` child. */ +const PARENT_FIRST_BODY = chain('parent_first_body', [step('second', 'u_exec')]); +const PARENT_FIRST = chain('parent_first', [step('first', 'u_mgr'), { id: 'sub', type: 'subflow', label: 'Second, in a child', config: { flowName: 'parent_first_body' } }]); +/** A batch with no record of its own: each item is a `doc_main` record, approved in its own `one` run. */ +const BATCH = { + name: 'batch', label: 'Batch', type: 'autolaunched', + variables: [{ name: 'items', type: 'list', isInput: true }], + nodes: [ + { id: 'bstart', type: 'start', label: 'Start' }, + { id: 'each', type: 'map', label: 'Each document', config: { collection: { dialect: 'cel', source: 'items' }, flowName: 'one', itemObject: 'doc_main' } }, + { id: 'bend', type: 'end', label: 'End' }, + ], + edges: [{ id: 'b1', source: 'bstart', target: 'each' }, { id: 'b2', source: 'each', target: 'bend' }], +}; + +async function packageObjects(): Promise { + let manifest: any; + const ctx: any = { + getService: (name: string) => { + if (name === 'manifest') return { register: (m: any) => { manifest = m; } }; + throw new Error(`no service '${name}'`); + }, + logger: silent, + }; + await new ApprovalsServicePlugin().init(ctx); + return manifest.objects; +} + +describe('ADR-0162 D5 — an abandoned approval never writes a closed value on its status mirror', () => { + let engine: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + let logger: ReturnType; + let seq = 0; + + beforeEach(async () => { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await engine.init(); + const users = { name: 'sys_user', label: 'User', fields: { id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, name: text('name'), email: text('email') } }; + for (const def of [users, ...OBJECTS, ...(await packageObjects())]) { + engine.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const id of [SUBMITTER, 'u_mgr', 'u_exec', 'u_root']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@example.test` }, { context: SYSTEM } as any); + } + logger = recordingLogger(); + svc = new ApprovalService({ engine: engine as any, logger }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); + automation = new AutomationEngine(silent, new InMemorySuspendedRunStore()); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + registerApprovalNode(automation as any, svc, silent); + for (const f of [ONE, TWO, CHILD_FIRST_BODY, CHILD_FIRST, PARENT_FIRST_BODY, PARENT_FIRST, BATCH]) automation.registerFlow(f.name, f as any); + svc.attachAutomation(automation as any); + }); + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const read = async (object: string, id: string) => + ((await engine.find(object, { where: { id }, context: SYSTEM } satisfies EngineQueryOptions)) as any[])[0]; + const statusOf = async (object: string, id: string) => (await read(object, id))?.approval_status ?? null; + const requestsOn = async (id: string): Promise => + engine.find('sys_approval_request', { where: { record_id: id }, context: SYSTEM } satisfies EngineQueryOptions) as any; + const pendingOn = async (id: string): Promise => { + const rows = (await requestsOn(id)).filter((r) => r.status === 'pending'); + expect(rows, `one pending request on ${id}`).toHaveLength(1); + return rows[0]; + }; + /** Another writer: a system write of the record's status while its request is pending. */ + const writeAsSystem = (object: string, id: string, value: unknown) => + engine.update(object, { id, approval_status: value }, { context: SYSTEM } as any); + /** + * Seed a record holding `atSubmit` and start `flow` on it. `snapshot` is the + * trigger record the flow starts from (the request's value at submit); + * by default the record as seeded. + */ + async function submit(object: string, opts: { atSubmit?: unknown; flow?: string; snapshot?: Record; name?: string | null } = {}) { + const id = `${object}_${++seq}`; + const seedRow: Record = { id, name: opts.name === undefined ? id : opts.name, organization_id: ORG }; + if (opts.atSubmit !== undefined) seedRow.approval_status = opts.atSubmit; + await engine.insert(object, seedRow, { context: SYSTEM } as any); + const record = opts.snapshot ? { id, name: seedRow.name, organization_id: ORG, ...opts.snapshot } : await read(object, id); + const run = await automation.execute(opts.flow ?? 'one', { object, record, userId: SUBMITTER } as any); + expect(run.status, JSON.stringify(run)).toBe('paused'); + return { id, request: await pendingOn(id) }; + } + const approve = async (request: any, decider: string) => svc.decide(request.id, { decision: 'approve', actorId: decider } as any, asUser(decider)); + + type Writer = 'submitter recall' | 'recall in the revise window' | 'administrator override' | 'system override' | 'dead-run sweep'; + const WRITERS: Writer[] = ['submitter recall', 'recall in the revise window', 'administrator override', 'system override', 'dead-run sweep']; + /** + * Abandon `request` by `writer`; the revise-window arm sends it back first. + * `before` runs just ahead of the abandoning call (after the send-back). + */ + async function abandon(request: any, writer: Writer = 'submitter recall', before?: () => Promise): Promise { + if (writer === 'recall in the revise window') { + await svc.sendBack(request.id, { actorId: 'u_mgr' } as any, asUser('u_mgr')); + } + await before?.(); + switch (writer) { + case 'submitter recall': + await svc.recall(request.id, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + break; + case 'recall in the revise window': + await svc.recall(request.id, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + break; + case 'administrator override': + await svc.recall(request.id, { actorId: 'u_root' } as any, ADMIN); + break; + case 'system override': + await svc.recall(request.id, { actorId: 'ops_bot' } as any, SYSTEM); + break; + case 'dead-run sweep': { + const dead = String(request.flow_run_id); + svc.attachAutomation({ getRun: async (runId: string) => ({ status: runId === dead ? 'failed' : 'paused' }) } as any); + try { await svc.releaseDeadRunRequests(); } finally { svc.attachAutomation(automation as any); } + break; + } + } + const after = (await requestsOn(request.record_id)).find((r) => r.id === request.id); + expect(after?.status, `${writer} abandoned the request`).toBe('recalled'); + } + const lines = (level: string, text: string) => logger.lines.filter((l: any) => l.level === level && l.msg.includes(text)); + + describe('across the writers that abandon a request (N20)', () => { + it.each(WRITERS)('%s: a closed value at submit is passed over for the default, and the pass is logged', async (writer) => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + expect(await statusOf('doc_main', id)).toBe('pending'); + await abandon(request, writer); + expect(await statusOf('doc_main', id)).toBe('draft'); + expect(lines('info', 'passed over')).toHaveLength(1); + }); + + it.each(WRITERS)('%s: a declared `recalled` the object closes on is withheld and logged; the field takes its value at submit', async (writer) => { + const { id, request } = await submit('doc_closed_recalled', { atSubmit: 'rejected' }); + await abandon(request, writer); + expect(await statusOf('doc_closed_recalled', id)).toBe('rejected'); + expect(lines('warn', "did not write 'recalled'")).toHaveLength(1); + }); + + it.each(WRITERS)('%s: a closed value the approval did not write is left alone, and that is logged', async (writer) => { + const { id, request } = await submit('doc_paid', { atSubmit: 'draft' }); + await abandon(request, writer, () => writeAsSystem('doc_paid', id, 'paid')); + expect(await statusOf('doc_paid', id)).toBe('paid'); + expect(lines('info', 'mirror writes nothing')).toHaveLength(1); + }); + + it.each(WRITERS)('%s CONTROL: on an object that closes on no value of the field, the value at submit is put back as before', async (writer) => { + const { id, request } = await submit('doc_control', { atSubmit: 'approved' }); + await abandon(request, writer); + expect(await statusOf('doc_control', id)).toBe('approved'); + expect(lines('info', 'passed over')).toEqual([]); + }); + }); + + describe('`recalled`', () => { + it('declared as an open value: written', async () => { + const { id, request } = await submit('doc_open_recalled', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_open_recalled', id)).toBe('recalled'); + expect(lines('warn', "did not write 'recalled'")).toEqual([]); + }); + + it('declared as a closed value: withheld, and a closed value at submit passed over for the default', async () => { + const { id, request } = await submit('doc_closed_recalled', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_closed_recalled', id)).toBe('draft'); + }); + + it('not declared: the field goes down the order (the value at submit)', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('rejected'); + }); + }); + + describe('the value at submit', () => { + it('open: put back', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('closed: passed over for the default', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('empty on a required field: passed over for the default', async () => { + const { id, request } = await submit('doc_required', { snapshot: { approval_status: null } }); + await abandon(request); + expect(await statusOf('doc_required', id)).toBe('draft'); + }); + + it('empty on a field that is not required: still put back', async () => { + const { id, request } = await submit('doc_main', { snapshot: { approval_status: null } }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBeNull(); + }); + + it('not carried by the request: the default', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected', snapshot: {} }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + }); + + describe('the default', () => { + it('usable: written', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('closed: passed over for empty, both passes logged', async () => { + const { id, request } = await submit('doc_default_closed', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_default_closed', id)).toBeNull(); + const [pass] = lines('info', 'passed over'); + expect(pass?.meta?.passedOver).toEqual([{ from: 'submit', value: 'approved' }, { from: 'default', value: 'approved' }]); + }); + + it('absent: empty', async () => { + const { id, request } = await submit('doc_no_default', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_no_default', id)).toBeNull(); + }); + }); + + describe('what the field holds when the request is abandoned', () => { + it("an open value, the request's own status, with a value at submit: the order", async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected' }); + expect(await statusOf('doc_main', id)).toBe('pending'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('rejected'); + }); + + it('an open value another writer put there, without a value at submit: the order', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'rejected', snapshot: {} }); + await writeAsSystem('doc_main', id, 'returned'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('a closed status no request of the approval had: left alone', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('approved'); + }); + + it('a closed status a request of another approval on the record had: left alone', async () => { + const first = await submit('doc_main', { atSubmit: 'draft' }); + await approve(first.request, 'u_mgr'); + expect(await statusOf('doc_main', first.id)).toBe('approved'); + const run = await automation.execute('one', { object: 'doc_main', record: await read('doc_main', first.id), userId: SUBMITTER } as any); + expect(run.status).toBe('paused'); + const second = await pendingOn(first.id); + await writeAsSystem('doc_main', first.id, 'approved'); + await abandon(second); + expect(await statusOf('doc_main', first.id)).toBe('approved'); + }); + }); + + describe('an object that closes on the field only on values of its own', () => { + it('such a value at submit is not put back: the default', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'paid' }); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('draft'); + }); + + it('such a value the approval did not write is left alone', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'draft' }); + await writeAsSystem('doc_own_values', id, 'paid'); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('paid'); + }); + + it('an approval status, open there, goes down the order as before: the value at submit', async () => { + const { id, request } = await submit('doc_own_values', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_own_values', id)).toBe('approved'); + }); + }); + + // The field declares no `pending`, so a later step's opening writes nothing + // and the earlier step's `approved` stays on the field: the shape of an + // approval its opening check did not judge (ADR-0162 Execution item 7). + describe("an earlier step's outcome on the field: the approval wrote it, so the field goes down the order", () => { + // [#37766 slice B] The check would refuse this approval at its first + // request (the field declares no `pending`). An approval it did not judge + // is one opened before the object declared `closedStates`: the request + // opens on the object as it stood, and the declaration comes after. + const NO_PENDING = OBJECTS.find((o) => o.name === 'doc_no_pending')!; + const submitBeforeDeclared = async (...args: Parameters) => { + const { closedStates: _later, ...undeclared } = NO_PENDING as typeof NO_PENDING & { closedStates?: unknown }; + engine.registry.registerObject(undeclared as any, 'approvals-test', 'approvals-test'); + try { return await submit(...args); } finally { + engine.registry.registerObject(NO_PENDING as any, 'approvals-test', 'approvals-test'); + } + }; + + it('that step in the same run', async () => { + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'approved', flow: 'two' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + + it('that step in a child run', async () => { + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'draft', flow: 'child_first' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + expect(second.root_run_id).toBe(request.root_run_id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + + it('that step in the parent of the run whose request is abandoned', async () => { + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'draft', flow: 'parent_first' }); + await approve(request, 'u_mgr'); + expect(await statusOf('doc_no_pending', id)).toBe('approved'); + const second = await pendingOn(id); + expect(second.flow_run_id).not.toBe(request.flow_run_id); + expect(second.root_run_id).toBe(request.root_run_id); + await abandon(second); + expect(await statusOf('doc_no_pending', id)).toBe('draft'); + }); + }); + + it("a `map` in which only another item's request had the value the field holds: left alone", async () => { + const items = ['map_a', 'map_b'].map((id) => ({ id, name: id, organization_id: ORG, approval_status: 'draft' })); + for (const item of items) await engine.insert('doc_main', item, { context: SYSTEM } as any); + const run = await automation.execute('batch', { params: { items }, userId: SUBMITTER } as any); + expect(run.status).toBe('paused'); + await approve(await pendingOn('map_a'), 'u_mgr'); + expect(await statusOf('doc_main', 'map_a')).toBe('approved'); + const b = await pendingOn('map_b'); + expect(b.root_run_id).toBe((await requestsOn('map_a'))[0].root_run_id); + await writeAsSystem('doc_main', 'map_b', 'approved'); + await abandon(b); + expect(await statusOf('doc_main', 'map_b')).toBe('approved'); + }); + + describe('where the mirror cannot tell, it goes down the order', () => { + it('the abandoned request records no root run (seat ruling 7210700837)', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.update('sys_approval_request', { id: request.id, root_run_id: null, root_run_started_at: null }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon({ ...request, root_run_id: null }); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('a request on the record that records no root run, opened since the approval started, had the value', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.insert('sys_approval_request', { + id: 'legacy_after', process_name: 'one', object_name: 'doc_main', record_id: id, status: 'approved', + organization_id: ORG, created_at: new Date(Date.now() + 1000).toISOString(), + }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('draft'); + }); + + it('a closed value that is no status of a request, on a request with no root run: left alone, since no request can have held it', async () => { + const { id, request } = await submit('doc_paid', { atSubmit: 'draft' }); + await engine.update('sys_approval_request', { id: request.id, root_run_id: null, root_run_started_at: null }, { context: SYSTEM } as any); + await writeAsSystem('doc_paid', id, 'paid'); + await abandon({ ...request, root_run_id: null }); + expect(await statusOf('doc_paid', id)).toBe('paid'); + }); + + it('CONTROL — the same request opened before the approval started does not count: left alone', async () => { + const { id, request } = await submit('doc_main', { atSubmit: 'draft' }); + await engine.insert('sys_approval_request', { + id: 'legacy_before', process_name: 'one', object_name: 'doc_main', record_id: id, status: 'approved', + organization_id: ORG, created_at: '2020-01-01T00:00:00.000Z', + }, { context: SYSTEM } as any); + await writeAsSystem('doc_main', id, 'approved'); + await abandon(request); + expect(await statusOf('doc_main', id)).toBe('approved'); + }); + }); + + describe('N17 — an empty put-back on each kind of required field, with no default: the value the field keeps', () => { + it('a required field that callers may edit: the validator refuses the empty write, which is reported, and the field keeps `pending`', async () => { + const { id, request } = await submit('doc_req_editable', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_editable', id)).toBe('pending'); + expect(lines('error', 'was NOT written')).toHaveLength(1); + }); + + it('a `readonly` required field: the empty write lands', async () => { + const { id, request } = await submit('doc_req_readonly', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_readonly', id)).toBeNull(); + }); + + it('a `system` required column: the empty write lands', async () => { + const { id, request } = await submit('doc_req_system', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_system', id)).toBeNull(); + }); + + it('a field required only when shown, and shown: the empty write is refused, and the field keeps `pending`', async () => { + const { id, request } = await submit('doc_req_when_shown', { atSubmit: 'approved' }); + await abandon(request); + expect(await statusOf('doc_req_when_shown', id)).toBe('pending'); + }); + + it('a field required only when shown, and hidden: the requirement is waived and the empty write lands', async () => { + const { id, request } = await submit('doc_req_when_shown', { atSubmit: 'approved', name: null }); + await abandon(request); + expect(await statusOf('doc_req_when_shown', id)).toBeNull(); + }); + + it('empty at submit on a required field with no default: empty is all that is left, and the refusal is the same', async () => { + const { id, request } = await submit('doc_req_editable', { snapshot: { approval_status: null }, atSubmit: 'draft' }); + await abandon(request); + expect(await statusOf('doc_req_editable', id)).toBe('pending'); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts new file mode 100644 index 00000000000..6fef6ef1b74 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts @@ -0,0 +1,349 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8] A write of the status mirror that a rule or a + * hook of the app refuses, on a field the object closes on, is not swallowed. + * + * The mirror writes as the system, and every control of the object still meets + * that write: a validation rule, an option's `visibleWhen` and a hook can each + * refuse it, and no reading of a definition shows when. On every field the + * mirror used to log such a refusal at `warn` and go on. On a field the object + * closes on at `approved` or `rejected` (`closedStates`), ADR-0162 D5 states + * what follows, by the write: + * + * - the `pending` of an approval's FIRST request: the approval does not open. + * The request's row, written first, is voided as `cancelled`; no lock is + * taken; the run fails at that step with the refusal's own message; the + * record keeps the value it held, a closed one included; + * - every other write: the field keeps the value it held, and the refusal is + * reported — an `error` line, a line with no actor on the request's + * timeline carrying the refusal's message, and a notice to the + * organization's administrators. + * + * Each test records the value the field keeps. The last one is the control: + * the same refusal on an object that declares no closed state is still the + * `warn` it was, and its approval opens. + * + * Real kernel, real ObjectQL engine with its validator and hooks, real + * automation engine, real approval node and record-lock hook, driver-sql on + * better-sqlite3 `:memory:`. The organization's administrators are stubbed at + * the one resolver the notice reads (`organizationAdministrators`): who holds + * that rung is pinned elsewhere (`admin-rescue-named-slate.integration.test.ts`). + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { bindApprovalLockHook } from './lifecycle-hooks.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +/** + * The status field, with the three controls of the app that can refuse the + * mirror's write, each armed by the record's own `block` field: + * - a `script` validation rule refuses the status `block` names; + * - the `draft` option's `visibleWhen` hides it while `block` is `draft`; + * - a hook (bound in `beforeEach`) refuses a status in {@link hookRefuses}. + * `recalled` is not declared, so an abandoned request puts the value at submit + * back. + */ +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: [ + { label: 'Draft', value: 'draft', visibleWhen: '!has(record.block) || record.block == null || record.block != "draft"' }, + ...['pending', 'approved', 'rejected', 'returned'].map((value) => ({ label: value, value })), + ], +}; +const blockRule = { + type: 'script' as const, name: 'blocked_status', message: 'This status is blocked by a rule of the app.', + condition: 'has(record.block) && record.block != null && record.approval_status == record.block', +}; +const invoiceFields = { name: text('name'), note: text('note'), block: text('block'), approval_status: statusField }; +/** Closes on its approval's outcome (ADR-0162 D1). */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields: invoiceFields, validations: [blockRule], closedStates: { approval_status: ['approved'] } }; +/** The same object, declaring no closed state: the control. */ +const memo = { name: 'crm_memo', label: 'Memo', fields: invoiceFields, validations: [blockRule] }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], lockRecord: true, approvalStatusField: 'approval_status' }, +}); +/** One step, with a revise window so a send-back can be resubmitted (ADR-0044). */ +const oneStep = { + name: 'one_step', label: 'One step', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('review', 'approver'), + { id: 'wait_revision', type: APPROVAL_REVISE_NODE_TYPE, label: 'Awaiting revision' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + { id: 'e4', source: 'review', target: 'wait_revision', label: 'revise' }, + { id: 'e5', source: 'wait_revision', target: 'review', label: 'resubmit', type: 'back' }, + ], +}; +const twoStep = { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('first', 'approver'), + step('second', 'approver2'), + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'first' }, + { id: 'e2', source: 'first', target: 'second', label: 'approve' }, + { id: 'e3', source: 'first', target: 'end', label: 'reject' }, + { id: 'e4', source: 'second', target: 'end', label: 'approve' }, + { id: 'e5', source: 'second', target: 'end', label: 'reject' }, + ], +}; + +const HOOK_REFUSAL = 'The hook refuses this status.'; + +describe('[ADR-0162 item 8] a refused write of the status mirror on a field the object closes on', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + let hookRefuses: Set; + let logs: Array<{ level: string; message: string; meta: any }>; + let emits: Array<{ topic: string; audience: string[]; source?: { object: string; id: string }; payload?: any }>; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + + hookRefuses = new Set(); + for (const object of ['crm_invoice', 'crm_memo']) { + ql.registerHook('beforeUpdate', async (ctx: any) => { + const status = (ctx.input?.data ?? {}).approval_status; + if (typeof status === 'string' && hookRefuses.has(status)) throw new Error(HOOK_REFUSAL); + }, { object }); + } + + logs = []; + const record = (level: string) => (message: unknown, a?: unknown, b?: unknown) => { + logs.push({ level, message: String(message), meta: level === 'error' ? b : a }); + }; + const logger = { debug: () => {}, info: () => {}, warn: record('warn'), error: record('error') }; + emits = []; + svc = new ApprovalService({ + engine: ql, logger: logger as any, + messaging: { emit: async (e: any) => { emits.push(e); } } as any, + }); + (svc as any).organizationAdministrators = async (org: unknown) => ({ ids: org === ORG ? ['org_admin'] : [] }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, logger as any); + bindApprovalLockHook(ql as any, logger as any); + automation.registerFlow(oneStep.name, oneStep as any); + automation.registerFlow(twoStep.name, twoStep as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) + .map((r: any) => ({ id: String(r.id), step: String(r.flow_node_id), status: String(r.status) })); + const timelineNotes = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId, action: 'comment' }, context: SYS })) + .map((r: any) => ({ actor: r.actor_id ?? null, comment: String(r.comment) })); + const inboxRows = async (requestId: string) => ql.find('sys_approval_approver', { where: { request_id: requestId }, context: SYS }); + const seed = (object: string, id: string, extra: Record = {}) => + ql.insert(object, { id, name: id, organization_id: ORG, ...extra }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (flow: string, object: string, id: string) => + automation.execute(flow, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + const open = async (flow: string, object: string, id: string) => { + const out = await start(flow, object, id); + expect(out.status, JSON.stringify(out)).toBe('paused'); + const pending = (await requestsOn(id)).filter((r) => r.status === 'pending'); + expect(pending).toHaveLength(1); + return pending[0].id; + }; + const errors = () => logs.filter((l) => l.level === 'error'); + const notices = () => emits.filter((e) => e.topic === 'approval.status_mirror_refused'); + /** The three parts of a report, for one refused write. */ + async function expectReported(object: string, id: string, requestId: string, status: string, reason: string) { + expect(errors().map((l) => l.meta), 'one error line, naming the write').toEqual([ + expect.objectContaining({ object, record: id, field: 'approval_status', value: status, request: requestId }), + ]); + expect(errors()[0].message).toContain('NOT written'); + expect(errors()[0].message, 'it names the fix').toContain('Change the rule or hook'); + expect(await timelineNotes(requestId), "a line with no actor, carrying the refusal's own message").toContainEqual({ + actor: null, comment: expect.stringContaining(reason), + }); + expect(notices().map((e) => ({ audience: e.audience, source: e.source })), "a notice to the organization's administrators") + .toEqual([{ audience: ['org_admin'], source: { object: 'sys_approval_request', id: requestId } }]); + } + + describe("the `pending` of an approval's first request", () => { + it('a validation rule refuses it: the approval does not open, the row is voided, the run fails with the rule\'s message, and the field keeps `draft`', async () => { + await seed('crm_invoice', 'i_rule', { block: 'pending' }); + + const out = await start('one_step', 'crm_invoice', 'i_rule'); + + expect(out.status).toBe('failed'); + expect(JSON.stringify(out), "the run fails with the refusal's own message").toContain(blockRule.message); + const [voided] = await requestsOn('i_rule'); + expect(await requestsOn('i_rule')).toEqual([{ id: voided.id, step: 'review', status: 'cancelled' }]); + expect(await field('crm_invoice', 'i_rule'), 'the value the field keeps').toBe('draft'); + expect(await inboxRows(voided.id), "nobody's inbox lists it").toEqual([]); + expect(await timelineNotes(voided.id)).toContainEqual({ actor: null, comment: expect.stringContaining(blockRule.message) }); + // No lock was taken: the owner edits the record at once. + await expect(ql.update('crm_invoice', { id: 'i_rule', note: 'edited' }, { context: asPerson('owner') })).resolves.toBeTruthy(); + // The submitter was told by the run's failure; nothing was lost, so this is no durability error. + expect(errors()).toEqual([]); + expect(notices()).toEqual([]); + }); + + it('a hook refuses it on a record closed on its last approval: the record stays closed on `approved`', async () => { + await seed('crm_invoice', 'i_closed', { approval_status: 'approved' }); + hookRefuses.add('pending'); + + const out = await start('one_step', 'crm_invoice', 'i_closed'); + + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain(HOOK_REFUSAL); + expect((await requestsOn('i_closed')).map((r) => r.status)).toEqual(['cancelled']); + expect(await field('crm_invoice', 'i_closed'), 'the value the field keeps').toBe('approved'); + }); + + it('a later submission of the same record, once the rule admits it, opens a new approval', async () => { + await seed('crm_invoice', 'i_again', { block: 'pending' }); + expect((await start('one_step', 'crm_invoice', 'i_again')).status).toBe('failed'); + await ql.update('crm_invoice', { id: 'i_again', block: null }, { context: SYS }); + + await open('one_step', 'crm_invoice', 'i_again'); + + expect((await requestsOn('i_again')).map((r) => r.status)).toEqual(['cancelled', 'pending']); + expect(await field('crm_invoice', 'i_again')).toBe('pending'); + }); + }); + + it("a later request's `pending` refused: the request stays open, the refusal is reported, and the field keeps `pending`", async () => { + await seed('crm_invoice', 'i_later'); + const first = await open('two_step', 'crm_invoice', 'i_later'); + hookRefuses.add('pending'); + + await svc.decide(first, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + + const [, second] = await requestsOn('i_later'); + expect(await requestsOn('i_later')).toEqual([ + { id: first, step: 'first', status: 'approved' }, + { id: second.id, step: 'second', status: 'pending' }, + ]); + // [ADR-0162 item 8, slice 3] The first step's decision is held back until + // the approval is over, so the field still holds the `pending` the first + // request wrote. + expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('pending'); + await expectReported('crm_invoice', 'i_later', second.id, 'pending', HOOK_REFUSAL); + }); + + it('the decision refused by a hook: the request is approved, the refusal is reported, and the field keeps `pending`', async () => { + await seed('crm_invoice', 'i_decide'); + const request = await open('one_step', 'crm_invoice', 'i_decide'); + hookRefuses.add('approved'); + + await svc.decide(request, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + + expect((await requestsOn('i_decide')).map((r) => r.status)).toEqual(['approved']); + expect(await field('crm_invoice', 'i_decide'), 'the value the field keeps').toBe('pending'); + await expectReported('crm_invoice', 'i_decide', request, 'approved', HOOK_REFUSAL); + expect(notices()[0].payload, 'the notice is about the record').toBeTruthy(); + }); + + it('the put-back of a recall refused by the `visibleWhen` of the value it puts back: the field keeps `pending`', async () => { + await seed('crm_invoice', 'i_recall'); + const request = await open('one_step', 'crm_invoice', 'i_recall'); + await ql.update('crm_invoice', { id: 'i_recall', block: 'draft' }, { context: SYS }); + + await svc.recall(request, { actorId: 'owner' } as any, asPerson('owner')); + + expect((await requestsOn('i_recall')).map((r) => r.status)).toEqual(['recalled']); + expect(await field('crm_invoice', 'i_recall'), 'the value the field keeps').toBe('pending'); + expect(errors()).toHaveLength(1); + expect(errors()[0].meta).toMatchObject({ object: 'crm_invoice', record: 'i_recall', value: 'recalled', request }); + expect(await timelineNotes(request)).toHaveLength(1); + expect(notices()).toHaveLength(1); + }); + + it('a send-back refused by a validation rule: the field keeps `pending`, and the refusal is reported', async () => { + await seed('crm_invoice', 'i_back'); + const request = await open('one_step', 'crm_invoice', 'i_back'); + await ql.update('crm_invoice', { id: 'i_back', block: 'returned' }, { context: SYS }); + + await svc.sendBack(request, { actorId: 'approver' } as any, asPerson('approver')); + + expect((await requestsOn('i_back')).map((r) => r.status)).toEqual(['returned']); + expect(await field('crm_invoice', 'i_back'), 'the value the field keeps').toBe('pending'); + await expectReported('crm_invoice', 'i_back', request, 'returned', blockRule.message); + }); + + it('CONTROL — the same refusal on an object that declares no closed state is the `warn` it was, and the approval opens', async () => { + await seed('crm_memo', 'm_rule', { block: 'pending' }); + + await open('one_step', 'crm_memo', 'm_rule'); + + expect((await requestsOn('m_rule')).map((r) => r.status)).toEqual(['pending']); + expect(await field('crm_memo', 'm_rule'), 'the value the field keeps').toBe('draft'); + expect(logs.filter((l) => l.level === 'warn' && l.message.includes('mirrorStatusField failed'))).toHaveLength(1); + expect(errors()).toEqual([]); + const [request] = await requestsOn('m_rule'); + expect(await timelineNotes(request.id)).toEqual([]); + expect(notices()).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts index ffba6519a24..ced440da7e7 100644 --- a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts +++ b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts @@ -172,6 +172,8 @@ describe('R7 — an open approval request gains the package that holds its flow' // ADR-0162 item 7 (the root run) adds these two, after this card. { fields: ['root_run_id', 'object_name', 'record_id'], unique: false }, { fields: ['record_run_id'], unique: false }, + // ADR-0162 item 8 (the mark) adds this one. + { fields: ['unjudged_since'], unique: false }, ])); expect((SysApprovalRequest.fields as Record).process_package).toMatchObject({ type: 'text', required: false, readonly: true, diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index f606582d10c..a12b49ea3bb 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -118,7 +118,7 @@ export const SysApprovalRequest = ObjectSchema.create({ searchableFields: [ 'process_name', 'process_package', 'process_label', 'object_name', 'record_id', 'submitter_comment', 'status', 'cancel_reason', 'current_step', 'current_step_label', 'pending_approvers', 'pending_approver_labels', - 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'node_config_json', + 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'between_steps_json', 'node_config_json', ], // Curated built-in list views — render as segmented tabs in the console. @@ -554,6 +554,38 @@ export const SysApprovalRequest = ObjectSchema.create({ group: 'State', }), + // [ADR-0162 Execution item 7] The nodes that stand between two steps of the + // request's approval: a JSON list of `{ flow, node }`, the flow by the key + // the engine files it under. The check when an approval opens works the set + // out at the approval's first request and stamps it on every request of + // the approval as it opens, so that a stop or a pause of the run can later + // be placed against it (ADR-0162 item 8). Engine-written at open and never + // re-derived; null on a request of an approval no step of which can act on + // an object that declares `closedStates`, and on one the plugin could not + // place. + between_steps_json: Field.textarea({ + label: 'Between Steps', + required: false, + readonly: true, + description: 'Flow nodes that stand between two steps of the approval this request belongs to.', + group: 'State', + }), + + // [ADR-0162 D5, Execution item 8] The mark: when the request was decided, + // while what follows that decision has not been judged yet. Set in the + // update that records an approve or a reject on a request of an approval + // the check stamped (`between_steps_json`), and cleared when the plugin + // has judged the approval: finished, abandoned, or moved on to its next + // request on the record. The store filters on it, oldest first, so that + // whatever no door judged can be found; null on every other request. + unjudged_since: Field.datetime({ + label: 'Unjudged Since', + required: false, + readonly: true, + description: 'When this request was decided, while what follows the decision has not been judged yet.', + group: 'State', + }), + node_config_json: Field.textarea({ label: 'Node Config', required: false, @@ -622,6 +654,8 @@ export const SysApprovalRequest = ObjectSchema.create({ { fields: ['root_run_id', 'object_name', 'record_id'] }, // Every request on the record one run carries. { fields: ['record_run_id'] }, + // [ADR-0162 Execution item 8] The decided requests whose approval is not judged yet, oldest first. + { fields: ['unjudged_since'] }, ], // Server-declared decision actions (objectui#2678 P2-4). The console's diff --git a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts index 15e13591861..ae1412ca4c4 100644 --- a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts @@ -117,6 +117,14 @@ export const arObjects: NonNullable = { label: "تشغيل السجل", help: "تشغيل الأتمتة الذي يحمل سجل هذا الطلب." }, + between_steps_json: { + label: "بين الخطوات", + help: "عُقد التدفق التي تقع بين خطوتين من الموافقة التي ينتمي إليها هذا الطلب." + }, + unjudged_since: { + label: "غير محسوم منذ", + help: "وقت البتّ في هذا الطلب، ما دام ما يلي القرار لم يُحسم بعد." + }, node_config_json: { label: "إعداد العقدة", help: "لقطة من إعداد عقدة الموافقة (الموافِقون/السلوك) للطلبات التي تقودها العُقد." diff --git a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts index f7a6e752006..eb6407dc6ac 100644 --- a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts @@ -117,6 +117,14 @@ export const deObjects: NonNullable = { label: "Datensatzausführung", help: "Automatisierungsausführung, die den Datensatz dieser Anfrage trägt." }, + between_steps_json: { + label: "Zwischen Schritten", + help: "Flussknoten, die zwischen zwei Schritten der Genehmigung stehen, zu der diese Anfrage gehört." + }, + unjudged_since: { + label: "Nicht beurteilt seit", + help: "Wann diese Anfrage entschieden wurde, solange noch nicht beurteilt ist, was auf die Entscheidung folgt." + }, node_config_json: { label: "Knotenkonfiguration", help: "Momentaufnahme der Konfiguration des Genehmigungsknotens (Genehmiger/Verhalten) bei knotengesteuerten Anfragen." diff --git a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts index 22a0e13f2e2..8b691d648b8 100644 --- a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts @@ -117,6 +117,14 @@ export const enObjects: NonNullable = { label: "Record Run", help: "Automation run that carries the record this request is on." }, + between_steps_json: { + label: "Between Steps", + help: "Flow nodes that stand between two steps of the approval this request belongs to." + }, + unjudged_since: { + label: "Unjudged Since", + help: "When this request was decided, while what follows the decision has not been judged yet." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts index 415a592b4b0..f9fb91e1361 100644 --- a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts @@ -117,6 +117,14 @@ export const esESObjects: NonNullable = { label: "Ejecución del registro", help: "Ejecución de automatización que lleva el registro de esta solicitud." }, + between_steps_json: { + label: "Entre pasos", + help: "Nodos del flujo que están entre dos pasos de la aprobación a la que pertenece esta solicitud." + }, + unjudged_since: { + label: "Sin evaluar desde", + help: "Cuándo se decidió esta solicitud, mientras aún no se ha evaluado lo que sigue a la decisión." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts index b02c1beb118..3f00197197e 100644 --- a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts @@ -117,6 +117,14 @@ export const frObjects: NonNullable = { label: "Exécution de l’enregistrement", help: "Exécution d’automatisation qui porte l’enregistrement de cette demande." }, + between_steps_json: { + label: "Entre les étapes", + help: "Nœuds du flux situés entre deux étapes de l'approbation à laquelle appartient cette demande." + }, + unjudged_since: { + label: "Non évaluée depuis", + help: "Date à laquelle cette demande a été décidée, tant que la suite de la décision n'a pas encore été évaluée." + }, node_config_json: { label: "Configuration du nœud", help: "Instantané de la configuration du nœud d’approbation (approbateurs/comportement) pour les demandes pilotées par un nœud." diff --git a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts index e3106fa79b9..df8aca292a8 100644 --- a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts @@ -117,6 +117,14 @@ export const jaJPObjects: NonNullable = { label: "レコード実行", help: "この申請の対象レコードを担う自動化実行。" }, + between_steps_json: { + label: "ステップ間", + help: "この申請が属する承認で、二つのステップの間にあるフローノード。" + }, + unjudged_since: { + label: "未判定の開始日時", + help: "この申請が決定された日時。その決定に続く処理がまだ判定されていない間だけ記録されます。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts index b0ebc188746..a36e7e8df6f 100644 --- a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts @@ -117,6 +117,14 @@ export const koObjects: NonNullable = { label: "레코드 실행", help: "이 요청이 걸린 레코드를 담고 있는 자동화 실행입니다." }, + between_steps_json: { + label: "단계 사이", + help: "이 요청이 속한 승인에서 두 단계 사이에 있는 플로 노드입니다." + }, + unjudged_since: { + label: "미판정 시작 시각", + help: "이 요청이 결정된 시각으로, 그 결정 이후의 진행이 아직 판정되지 않은 동안 기록됩니다." + }, node_config_json: { label: "노드 구성", help: "노드 기반 요청의 승인 노드 구성(승인자/동작) 스냅숏입니다." diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 7f8b399c79d..5f995e5dcd9 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -120,6 +120,21 @@ const enSentences = { approvalReminderBody: 'A decision on {{object}} {{record}} is still waiting on you.', approvalSlaBreachedTitle: 'Approval SLA breached', approvalSlaBreachedBody: 'A decision on {{object}} {{record}} is overdue.', + approvalStatusMirrorRefusedTitle: 'Approval status not written', + approvalStatusMirrorRefusedBody: 'The approval status of {{object}} {{record}} was refused by a rule or hook of the app: {{reason}} Change that rule or hook so the status can be written.', + approvalOpeningRefusedLead: 'The approval of {{object}} {{record}} was not started: the object closes on its approval field, and the approval cannot show itself in progress there.', + approvalOpeningRefusedClosedStatesLead: 'The approval of {{object}} {{record}} was not started: it can act on an object that declares closedStates.', + approvalOpeningNoPendingOption: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field\'s options.', + approvalOpeningClosesInFlight: '{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object\'s closedStates.', + approvalOpeningStateMachine: 'The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.', + approvalOpeningReadonlyWhen: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a readonlyWhen; remove it.', + approvalOpeningOptionVisibleWhen: 'The option {{value}} of field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a visibleWhen; remove it.', + approvalOpeningOtherField: 'Step {{step}} of flow {{flow}} can act on {{object}} but mirrors onto field {{other}}; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningNoField: 'Step {{step}} of flow {{flow}} can act on {{object}} but names no approval status field; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningPause: 'Node {{node}} ({{type}}) of flow {{flow}} can pause the run between two approval steps of {{object}}; move it before the first step or after the last.', + approvalOpeningMapApproval: 'The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.', + approvalOpeningUnreadableFlow: 'Flow {{flow}}, which the approval runs, could not be read, so the approval cannot be checked.', + approvalOpeningNoJobService: '{{object}} declares closedStates, and this host runs no job service, so nothing would end an approval nobody finishes; install a job service.', approvalSlaBreachedSubmitterTitle: 'Your approval request breached its SLA', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: escalation action '{{action}}' was taken.", approvalApprovedTitle: 'Request approved', @@ -138,6 +153,10 @@ const enSentences = { approvalReassignedBody: 'You are now an approver on {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approval auto-rejected', approvalAutoRejectedBody: 'Your {{object}} {{record}} exceeded the revision limit ({{limit}}) and was rejected.', + approvalAbandonedTitle: 'Approval did not finish', + approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', + approvalFlowNotContinuedTitle: 'Approval flow could not be seen through to its end', + approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow could not be seen through to its end after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where it has ended or no run is left, check that the steps after the decision were done.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -253,6 +272,21 @@ export const zhCNMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} 仍在等待您的审批决定。', approvalSlaBreachedTitle: '审批已超出时限', approvalSlaBreachedBody: '{{object}} {{record}} 的审批决定已逾期。', + approvalStatusMirrorRefusedTitle: '审批状态未能写入', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的审批状态被应用自己的规则或钩子拒绝:{{reason}} 请修改该规则或钩子,使状态可以写入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的审批没有发起:该对象会在审批字段上关闭,而这次审批无法在该字段上显示「审批中」。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} 的审批没有发起:它可能作用到一个声明了 closedStates 的对象。', + approvalOpeningNoPendingOption: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。', + approvalOpeningClosesInFlight: '{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。', + approvalOpeningStateMachine: '{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})带有 readonlyWhen;请去掉它。', + approvalOpeningOptionVisibleWhen: '{{object}} 字段 {{field}} 的选项 {{value}}(流程 {{flow}} 的步骤 {{step}})带有 visibleWhen;请去掉它。', + approvalOpeningOtherField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却把状态写到字段 {{other}};凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却没有指定审批状态字段;凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的节点 {{node}}({{type}})可能在 {{object}} 的两个审批步骤之间暂停运行;请把它移到第一步之前或最后一步之后。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。', + approvalOpeningUnreadableFlow: '审批要运行的流程 {{flow}} 无法读取,因此无法检查这次审批。', + approvalOpeningNoJobService: '{{object}} 声明了 closedStates,而本宿主没有运行 job 服务,没人完成的审批将无法结束;请安装 job 服务。', approvalSlaBreachedSubmitterTitle: '您的审批请求已超出时限', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已执行升级操作「{{action}}」。', approvalApprovedTitle: '请求已批准', @@ -271,6 +305,10 @@ export const zhCNMessages: ApprovalMessages = { approvalReassignedBody: '您现在是 {{object}} {{record}} 的审批人。', approvalAutoRejectedTitle: '审批已自动驳回', approvalAutoRejectedBody: '您的{{object}} {{record}} 已超过退回修改次数上限({{limit}}),已被驳回。', + approvalAbandonedTitle: '审批未能完成', + approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', + approvalFlowNotContinuedTitle: '无法确认审批流程已执行到结束', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但无法确认其流程在该步之后已执行到结束,之后的步骤可能没有执行。请检查该审批的流程运行:若仍处于暂停,请继续或取消它;若运行已结束或已无运行记录,请核对该决定之后的步骤是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -323,6 +361,21 @@ export const jaJPMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} について、引き続きあなたの承認判断をお待ちしています。', approvalSlaBreachedTitle: '承認の期限超過', approvalSlaBreachedBody: '{{object}} {{record}} の承認判断が期限を過ぎています。', + approvalStatusMirrorRefusedTitle: '承認ステータスを書き込めませんでした', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} の承認ステータスは、アプリのルールまたはフックに拒否されました:{{reason}} ステータスを書き込めるよう、そのルールまたはフックを変更してください。', + approvalOpeningRefusedLead: '{{object}} {{record}} の承認は開始されませんでした:このオブジェクトは承認フィールドでクローズしますが、この承認はそのフィールドに承認中を表示できません。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} の承認は開始されませんでした:この承認は closedStates を宣言するオブジェクトに作用する可能性があります。', + approvalOpeningNoPendingOption: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。', + approvalOpeningClosesInFlight: '{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。', + approvalOpeningStateMachine: '{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。', + approvalOpeningReadonlyWhen: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})に readonlyWhen があります。削除してください。', + approvalOpeningOptionVisibleWhen: '{{object}} のフィールド {{field}} の選択肢 {{value}}(フロー {{flow}} のステップ {{step}})に visibleWhen があります。削除してください。', + approvalOpeningOtherField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、フィールド {{other}} にステータスを書き込みます。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningNoField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、承認ステータスフィールドを指定していません。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningPause: 'フロー {{flow}} のノード {{node}}({{type}})は {{object}} の二つの承認ステップの間で実行を一時停止する可能性があります。最初のステップの前か最後のステップの後に移動してください。', + approvalOpeningMapApproval: 'フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。', + approvalOpeningUnreadableFlow: '承認が実行するフロー {{flow}} を読み取れなかったため、承認を確認できません。', + approvalOpeningNoJobService: '{{object}} は closedStates を宣言していますが、このホストでは job サービスが動いていないため、誰も完了しない承認を終わらせるものがありません。job サービスをインストールしてください。', approvalSlaBreachedSubmitterTitle: 'あなたの承認申請が期限を超過しました', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:エスカレーション操作「{{action}}」が実行されました。', approvalApprovedTitle: '申請が承認されました', @@ -341,6 +394,10 @@ export const jaJPMessages: ApprovalMessages = { approvalReassignedBody: 'あなたは {{object}} {{record}} の承認者になりました。', approvalAutoRejectedTitle: '承認が自動的に却下されました', approvalAutoRejectedBody: 'あなたの{{object}} {{record}} は差し戻し回数の上限({{limit}})を超えたため却下されました。', + approvalAbandonedTitle: '承認が完了しませんでした', + approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', + approvalFlowNotContinuedTitle: '承認フローが最後まで実行されたか確認できません', + approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に最後まで実行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認してください。まだ一時停止中であれば続行またはキャンセルし、実行が終了しているか残っていなければ、決定の後のステップが行われたかを確認してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -393,6 +450,21 @@ export const esESMessages: ApprovalMessages = { approvalReminderBody: 'Una decisión sobre {{object}} {{record}} sigue pendiente de usted.', approvalSlaBreachedTitle: 'Plazo de aprobación incumplido', approvalSlaBreachedBody: 'La decisión sobre {{object}} {{record}} está vencida.', + approvalStatusMirrorRefusedTitle: 'No se escribió el estado de aprobación', + approvalStatusMirrorRefusedBody: 'Una regla o un hook de la aplicación rechazó el estado de aprobación de {{object}} {{record}}: {{reason}} Cambie esa regla o ese hook para que el estado pueda escribirse.', + approvalOpeningRefusedLead: 'No se inició la aprobación de {{object}} {{record}}: el objeto se cierra en su campo de aprobación y la aprobación no puede mostrarse en curso en él.', + approvalOpeningRefusedClosedStatesLead: 'No se inició la aprobación de {{object}} {{record}}: puede actuar sobre un objeto que declara closedStates.', + approvalOpeningNoPendingOption: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.', + approvalOpeningClosesInFlight: '{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.', + approvalOpeningStateMachine: 'La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.', + approvalOpeningReadonlyWhen: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un readonlyWhen; quítelo.', + approvalOpeningOptionVisibleWhen: 'La opción {{value}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un visibleWhen; quítelo.', + approvalOpeningOtherField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero escribe en el campo {{other}}; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningNoField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero no nombra ningún campo de estado de aprobación; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningPause: 'El nodo {{node}} ({{type}}) del flujo {{flow}} puede pausar la ejecución entre dos pasos de aprobación de {{object}}; muévalo antes del primer paso o después del último.', + approvalOpeningMapApproval: 'El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.', + approvalOpeningUnreadableFlow: 'No se pudo leer el flujo {{flow}}, que la aprobación ejecuta, así que no se puede comprobar la aprobación.', + approvalOpeningNoJobService: '{{object}} declara closedStates y este host no ejecuta ningún servicio job, así que nada terminaría una aprobación que nadie complete; instale un servicio job.', approvalSlaBreachedSubmitterTitle: 'Su solicitud de aprobación ha superado su plazo', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: se ha ejecutado la acción de escalado '{{action}}'.", approvalApprovedTitle: 'Solicitud aprobada', @@ -411,6 +483,10 @@ export const esESMessages: ApprovalMessages = { approvalReassignedBody: 'Ahora es aprobador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprobación rechazada automáticamente', approvalAutoRejectedBody: 'Su {{object}} {{record}} superó el límite de revisiones ({{limit}}) y se ha rechazado.', + approvalAbandonedTitle: 'La aprobación no terminó', + approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', + approvalFlowNotContinuedTitle: 'No se pudo comprobar que el flujo de la aprobación llegara al final', + approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se pudo comprobar que su flujo continuara hasta el final después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya terminó o no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -463,6 +539,21 @@ export const zhHantMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}} 仍在等待你的核准決定。', approvalSlaBreachedTitle: '核准已逾時', approvalSlaBreachedBody: '{{object}} {{record}} 的核准決定已逾期。', + approvalStatusMirrorRefusedTitle: '核准狀態未能寫入', + approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的核准狀態被應用程式自己的規則或掛鉤拒絕:{{reason}} 請修改該規則或掛鉤,讓狀態可以寫入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的核准沒有發起:該物件會在核准欄位上關閉,而這次核准無法在該欄位上顯示「核准中」。', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}} 的核准沒有發起:它可能作用到一個宣告了 closedStates 的物件。', + approvalOpeningNoPendingOption: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。', + approvalOpeningClosesInFlight: '{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。', + approvalOpeningStateMachine: '{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})帶有 readonlyWhen;請移除它。', + approvalOpeningOptionVisibleWhen: '{{object}} 欄位 {{field}} 的選項 {{value}}(流程 {{flow}} 的步驟 {{step}})帶有 visibleWhen;請移除它。', + approvalOpeningOtherField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻把狀態寫到欄位 {{other}};凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻沒有指定核准狀態欄位;凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的節點 {{node}}({{type}})可能在 {{object}} 的兩個核准步驟之間暫停執行;請把它移到第一步之前或最後一步之後。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。', + approvalOpeningUnreadableFlow: '核准要執行的流程 {{flow}} 無法讀取,因此無法檢查這次核准。', + approvalOpeningNoJobService: '{{object}} 宣告了 closedStates,而本主機沒有執行 job 服務,沒有人完成的核准將無法結束;請安裝 job 服務。', approvalSlaBreachedSubmitterTitle: '你的核准請求已逾時', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已執行升級動作「{{action}}」。', approvalApprovedTitle: '請求已核准', @@ -481,6 +572,10 @@ export const zhHantMessages: ApprovalMessages = { approvalReassignedBody: '你現在是 {{object}} {{record}} 的核准人。', approvalAutoRejectedTitle: '核准已自動駁回', approvalAutoRejectedBody: '你的{{object}} {{record}} 已超過退回修改次數上限({{limit}}),因此被駁回。', + approvalAbandonedTitle: '核准未能完成', + approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', + approvalFlowNotContinuedTitle: '無法確認核准流程已執行到結束', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但無法確認其流程在該步之後已執行到結束,之後的步驟可能沒有執行。請檢查該核准的流程執行:若仍處於暫停,請繼續或取消它;若執行已結束或已無執行記錄,請核對該決定之後的步驟是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -533,6 +628,21 @@ export const arMessages: ApprovalMessages = { approvalReminderBody: 'قرار بشأن {{object}} {{record}} لا يزال بانتظارك.', approvalSlaBreachedTitle: 'تجاوزت الموافقة مهلتها', approvalSlaBreachedBody: 'القرار بشأن {{object}} {{record}} متأخر.', + approvalStatusMirrorRefusedTitle: 'لم تُكتب حالة الموافقة', + approvalStatusMirrorRefusedBody: 'رفضت قاعدة أو خطّاف في التطبيق حالة الموافقة على {{object}} {{record}}: {{reason}} غيّر تلك القاعدة أو ذلك الخطّاف لكي تُكتب الحالة.', + approvalOpeningRefusedLead: 'لم تبدأ الموافقة على {{object}} {{record}}: الكائن يُغلَق على حقل الموافقة، والموافقة لا تستطيع أن تُظهر فيه أنها جارية.', + approvalOpeningRefusedClosedStatesLead: 'لم تبدأ الموافقة على {{object}} {{record}}: قد تعمل على كائن يُعلن closedStates.', + approvalOpeningNoPendingOption: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.', + approvalOpeningClosesInFlight: 'يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.', + approvalOpeningStateMachine: 'قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.', + approvalOpeningReadonlyWhen: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل readonlyWhen؛ أزله.', + approvalOpeningOptionVisibleWhen: 'الخيار {{value}} من الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل visibleWhen؛ أزله.', + approvalOpeningOtherField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها تكتب الحالة في الحقل {{other}}؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningNoField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها لا تسمّي حقلًا لحالة الموافقة؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningPause: 'العقدة {{node}} ({{type}}) في التدفق {{flow}} قد توقف التشغيل مؤقتًا بين خطوتَي موافقة على {{object}}؛ انقلها قبل الخطوة الأولى أو بعد الأخيرة.', + approvalOpeningMapApproval: 'عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.', + approvalOpeningUnreadableFlow: 'تعذّرت قراءة التدفق {{flow}} الذي تشغّله الموافقة، لذا لا يمكن فحص الموافقة.', + approvalOpeningNoJobService: 'يصرّح {{object}} بـ closedStates، وهذا المضيف لا يشغّل خدمة job، فلا شيء سينهي موافقة لا يكملها أحد؛ ثبّت خدمة job.', approvalSlaBreachedSubmitterTitle: 'تجاوز طلب الموافقة الخاص بك مهلته', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: نُفِّذ إجراء التصعيد «{{action}}».', approvalApprovedTitle: 'تمت الموافقة على الطلب', @@ -551,6 +661,10 @@ export const arMessages: ApprovalMessages = { approvalReassignedBody: 'أصبحت الآن موافِقًا على {{object}} {{record}}.', approvalAutoRejectedTitle: 'رُفضت الموافقة تلقائيًا', approvalAutoRejectedBody: 'تجاوز طلبك بشأن {{object}} {{record}} حد المراجعات ({{limit}}) فرُفض.', + approvalAbandonedTitle: 'لم تكتمل الموافقة', + approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', + approvalFlowNotContinuedTitle: 'تعذّر التأكد من أن مسار الموافقة استمر حتى نهايته', + approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن تعذّر التأكد من أن مسارها استمر حتى نهايته بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة: إن كان لا يزال متوقفًا مؤقتًا فتابعه أو ألغِه، وإن كان قد انتهى أو لم يبقَ له تشغيل فتحقّق من أن الخطوات التي تلي القرار قد نُفّذت.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -603,6 +717,21 @@ export const frMessages: ApprovalMessages = { approvalReminderBody: 'Une décision sur {{object}} {{record}} vous attend toujours.', approvalSlaBreachedTitle: 'Délai d’approbation dépassé', approvalSlaBreachedBody: 'La décision sur {{object}} {{record}} est en retard.', + approvalStatusMirrorRefusedTitle: 'Statut d’approbation non écrit', + approvalStatusMirrorRefusedBody: 'Une règle ou un hook de l’application a refusé le statut d’approbation de {{object}} {{record}} : {{reason}} Modifiez cette règle ou ce hook pour que le statut puisse être écrit.', + approvalOpeningRefusedLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : l\'objet se ferme sur son champ d\'approbation, et l\'approbation ne peut pas s\'y afficher en cours.', + approvalOpeningRefusedClosedStatesLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : elle peut agir sur un objet qui déclare closedStates.', + approvalOpeningNoPendingOption: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.', + approvalOpeningClosesInFlight: '{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d\'approbation en cours ; retirez {{value}} des closedStates de l\'objet.', + approvalOpeningStateMachine: 'La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.', + approvalOpeningReadonlyWhen: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un readonlyWhen ; retirez-le.', + approvalOpeningOptionVisibleWhen: 'L\'option {{value}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un visibleWhen ; retirez-le.', + approvalOpeningOtherField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais écrit dans le champ {{other}} ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningNoField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais ne nomme aucun champ de statut d\'approbation ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningPause: 'Le nœud {{node}} ({{type}}) du flux {{flow}} peut mettre l\'exécution en pause entre deux étapes d\'approbation de {{object}} ; placez-le avant la première étape ou après la dernière.', + approvalOpeningMapApproval: 'Le nœud map {{node}} du flux {{flow}} exécute une étape d\'approbation pour chaque élément, et le nœud ne montre pas qu\'aucun élément n\'est un enregistrement ; l\'approbation d\'un autre enregistrement retiendrait {{object}} entre deux étapes.', + approvalOpeningUnreadableFlow: 'Le flux {{flow}}, que l\'approbation exécute, n\'a pas pu être lu ; l\'approbation ne peut donc pas être vérifiée.', + approvalOpeningNoJobService: '{{object}} déclare closedStates et cet hôte n\'exécute aucun service job : rien ne terminerait une approbation que personne n\'achève ; installez un service job.', approvalSlaBreachedSubmitterTitle: 'Votre demande d’approbation a dépassé son délai', approvalSlaBreachedSubmitterBody: '{{object}} {{record}} : l’action d’escalade « {{action}} » a été exécutée.', approvalApprovedTitle: 'Demande approuvée', @@ -621,6 +750,10 @@ export const frMessages: ApprovalMessages = { approvalReassignedBody: 'Vous êtes désormais approbateur de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approbation rejetée automatiquement', approvalAutoRejectedBody: 'Votre demande sur {{object}} {{record}} a dépassé la limite de révisions ({{limit}}) et a été rejetée.', + approvalAbandonedTitle: 'L’approbation n’a pas abouti', + approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', + approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas pu être vérifié jusqu’à son terme', + approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais il n’a pas pu être vérifié que son flux s’est poursuivi jusqu’à son terme après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; si elle est terminée ou s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -673,6 +806,21 @@ export const ptBRMessages: ApprovalMessages = { approvalReminderBody: 'Uma decisão sobre {{object}} {{record}} ainda está aguardando você.', approvalSlaBreachedTitle: 'Prazo de aprovação estourado', approvalSlaBreachedBody: 'A decisão sobre {{object}} {{record}} está atrasada.', + approvalStatusMirrorRefusedTitle: 'Status de aprovação não gravado', + approvalStatusMirrorRefusedBody: 'Uma regra ou um hook do aplicativo recusou o status de aprovação de {{object}} {{record}}: {{reason}} Altere essa regra ou esse hook para que o status possa ser gravado.', + approvalOpeningRefusedLead: 'A aprovação de {{object}} {{record}} não foi iniciada: o objeto é fechado no seu campo de aprovação, e a aprovação não consegue se mostrar em andamento nele.', + approvalOpeningRefusedClosedStatesLead: 'A aprovação de {{object}} {{record}} não foi iniciada: ela pode agir sobre um objeto que declara closedStates.', + approvalOpeningNoPendingOption: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.', + approvalOpeningClosesInFlight: '{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.', + approvalOpeningStateMachine: 'A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.', + approvalOpeningReadonlyWhen: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um readonlyWhen; remova-o.', + approvalOpeningOptionVisibleWhen: 'A opção {{value}} do campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um visibleWhen; remova-o.', + approvalOpeningOtherField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas grava no campo {{other}}; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningNoField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas não indica nenhum campo de status de aprovação; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningPause: 'O nó {{node}} ({{type}}) do fluxo {{flow}} pode pausar a execução entre duas etapas de aprovação de {{object}}; mova-o para antes da primeira etapa ou depois da última.', + approvalOpeningMapApproval: 'O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.', + approvalOpeningUnreadableFlow: 'O fluxo {{flow}}, que a aprovação executa, não pôde ser lido, então a aprovação não pode ser verificada.', + approvalOpeningNoJobService: '{{object}} declara closedStates e este host não executa nenhum serviço job, então nada encerraria uma aprovação que ninguém conclua; instale um serviço job.', approvalSlaBreachedSubmitterTitle: 'Sua solicitação de aprovação estourou o prazo', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: a ação de escalonamento "{{action}}" foi executada.', approvalApprovedTitle: 'Solicitação aprovada', @@ -691,6 +839,10 @@ export const ptBRMessages: ApprovalMessages = { approvalReassignedBody: 'Agora você é aprovador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprovação rejeitada automaticamente', approvalAutoRejectedBody: 'Sua solicitação sobre {{object}} {{record}} excedeu o limite de revisões ({{limit}}) e foi rejeitada.', + approvalAbandonedTitle: 'A aprovação não foi concluída', + approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', + approvalFlowNotContinuedTitle: 'Não foi possível confirmar que o fluxo da aprovação foi até o fim', + approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não foi possível confirmar que o fluxo continuou até o fim depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se já tiver terminado ou não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -743,6 +895,21 @@ export const ruMessages: ApprovalMessages = { approvalReminderBody: 'Решение по {{object}} {{record}} всё ещё ждёт вас.', approvalSlaBreachedTitle: 'Срок согласования нарушен', approvalSlaBreachedBody: 'Решение по {{object}} {{record}} просрочено.', + approvalStatusMirrorRefusedTitle: 'Статус согласования не записан', + approvalStatusMirrorRefusedBody: 'Правило или хук приложения отклонили статус согласования для {{object}} {{record}}: {{reason}} Измените это правило или хук, чтобы статус можно было записать.', + approvalOpeningRefusedLead: 'Согласование {{object}} {{record}} не запущено: объект закрывается по своему полю согласования, а согласование не может показать в нём, что оно идёт.', + approvalOpeningRefusedClosedStatesLead: 'Согласование {{object}} {{record}} не запущено: оно может действовать на объект, который объявляет closedStates.', + approvalOpeningNoPendingOption: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.', + approvalOpeningClosesInFlight: '{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.', + approvalOpeningStateMachine: 'Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.', + approvalOpeningReadonlyWhen: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет readonlyWhen; уберите его.', + approvalOpeningOptionVisibleWhen: 'Вариант {{value}} поля {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет visibleWhen; уберите его.', + approvalOpeningOtherField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но записывает статус в поле {{other}}; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningNoField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но не называет поле статуса согласования; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningPause: 'Узел {{node}} ({{type}}) процесса {{flow}} может приостановить выполнение между двумя шагами согласования {{object}}; перенесите его до первого шага или после последнего.', + approvalOpeningMapApproval: 'Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.', + approvalOpeningUnreadableFlow: 'Не удалось прочитать процесс {{flow}}, который запускает согласование, поэтому согласование нельзя проверить.', + approvalOpeningNoJobService: '{{object}} объявляет closedStates, а на этом хосте не работает служба job, поэтому согласование, которое никто не завершит, ничто не закончит; установите службу job.', approvalSlaBreachedSubmitterTitle: 'Ваш запрос на согласование нарушил срок', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: выполнено действие эскалации «{{action}}».', approvalApprovedTitle: 'Запрос одобрен', @@ -761,6 +928,10 @@ export const ruMessages: ApprovalMessages = { approvalReassignedBody: 'Теперь вы согласующий по {{object}} {{record}}.', approvalAutoRejectedTitle: 'Согласование отклонено автоматически', approvalAutoRejectedBody: 'Ваш запрос по {{object}} {{record}} превысил лимит доработок ({{limit}}) и был отклонён.', + approvalAbandonedTitle: 'Согласование не завершено', + approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', + approvalFlowNotContinuedTitle: 'Не удалось убедиться, что процесс согласования дошёл до конца', + approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не удалось убедиться, что процесс после этого шага дошёл до конца, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования: если он ещё приостановлен, продолжите или отмените его; если он завершился или запуска уже нет, проверьте, что шаги после решения выполнены.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -813,6 +984,21 @@ export const deMessages: ApprovalMessages = { approvalReminderBody: 'Eine Entscheidung zu {{object}} {{record}} wartet noch auf Sie.', approvalSlaBreachedTitle: 'Genehmigungsfrist überschritten', approvalSlaBreachedBody: 'Die Entscheidung zu {{object}} {{record}} ist überfällig.', + approvalStatusMirrorRefusedTitle: 'Genehmigungsstatus nicht geschrieben', + approvalStatusMirrorRefusedBody: 'Eine Regel oder ein Hook der App hat den Genehmigungsstatus von {{object}} {{record}} abgelehnt: {{reason}} Ändern Sie diese Regel oder diesen Hook, damit der Status geschrieben werden kann.', + approvalOpeningRefusedLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Das Objekt schließt auf seinem Genehmigungsfeld, und die Genehmigung kann sich dort nicht als laufend zeigen.', + approvalOpeningRefusedClosedStatesLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Sie kann auf ein Objekt wirken, das closedStates deklariert.', + approvalOpeningNoPendingOption: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.', + approvalOpeningClosesInFlight: '{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.', + approvalOpeningStateMachine: 'Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.', + approvalOpeningReadonlyWhen: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein readonlyWhen; entfernen Sie es.', + approvalOpeningOptionVisibleWhen: 'Die Option {{value}} des Feldes {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein visibleWhen; entfernen Sie es.', + approvalOpeningOtherField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, schreibt aber in das Feld {{other}}; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningNoField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, nennt aber kein Genehmigungsstatusfeld; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningPause: 'Der Knoten {{node}} ({{type}}) des Flows {{flow}} kann den Lauf zwischen zwei Genehmigungsschritten von {{object}} anhalten; verschieben Sie ihn vor den ersten oder hinter den letzten Schritt.', + approvalOpeningMapApproval: 'Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.', + approvalOpeningUnreadableFlow: 'Der Flow {{flow}}, den die Genehmigung ausführt, konnte nicht gelesen werden, daher kann die Genehmigung nicht geprüft werden.', + approvalOpeningNoJobService: '{{object}} deklariert closedStates, und dieser Host betreibt keinen job-Dienst, sodass nichts eine Genehmigung beenden würde, die niemand abschließt; installieren Sie einen job-Dienst.', approvalSlaBreachedSubmitterTitle: 'Ihre Genehmigungsanfrage hat ihre Frist überschritten', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: Die Eskalationsaktion „{{action}}“ wurde ausgeführt.', approvalApprovedTitle: 'Anfrage genehmigt', @@ -831,6 +1017,10 @@ export const deMessages: ApprovalMessages = { approvalReassignedBody: 'Sie sind jetzt Genehmiger für {{object}} {{record}}.', approvalAutoRejectedTitle: 'Genehmigung automatisch abgelehnt', approvalAutoRejectedBody: 'Ihre Anfrage zu {{object}} {{record}} hat das Überarbeitungslimit ({{limit}}) überschritten und wurde abgelehnt.', + approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', + approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', + approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung ließ sich nicht bis zum Ende nachvollziehen', + approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber es ließ sich nicht feststellen, dass ihr Ablauf nach diesem Schritt bis zum Ende fortgesetzt wurde, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist er beendet oder kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -883,6 +1073,21 @@ export const koMessages: ApprovalMessages = { approvalReminderBody: '{{object}} {{record}}에 대한 결정이 아직 회원님을 기다리고 있습니다.', approvalSlaBreachedTitle: '승인 기한 초과', approvalSlaBreachedBody: '{{object}} {{record}}에 대한 결정이 기한을 넘겼습니다.', + approvalStatusMirrorRefusedTitle: '승인 상태를 기록하지 못했습니다', + approvalStatusMirrorRefusedBody: '앱의 규칙 또는 훅이 {{object}} {{record}}의 승인 상태를 거부했습니다: {{reason}} 상태를 기록할 수 있도록 해당 규칙 또는 훅을 변경하세요.', + approvalOpeningRefusedLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 개체는 승인 필드에서 닫히는데, 이 승인은 그 필드에 진행 중임을 표시할 수 없습니다.', + approvalOpeningRefusedClosedStatesLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 승인은 closedStates를 선언한 개체에 작용할 수 있습니다.', + approvalOpeningNoPendingOption: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.', + approvalOpeningClosesInFlight: '{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.', + approvalOpeningStateMachine: '{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.', + approvalOpeningReadonlyWhen: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})에 readonlyWhen이 있습니다. 제거하세요.', + approvalOpeningOptionVisibleWhen: '{{object}}의 필드 {{field}}의 옵션 {{value}}(흐름 {{flow}}의 단계 {{step}})에 visibleWhen이 있습니다. 제거하세요.', + approvalOpeningOtherField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 필드 {{other}}에 상태를 기록합니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningNoField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 승인 상태 필드를 지정하지 않습니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningPause: '흐름 {{flow}}의 노드 {{node}}({{type}})는 {{object}}의 두 승인 단계 사이에서 실행을 일시 중지할 수 있습니다. 첫 단계 앞이나 마지막 단계 뒤로 옮기세요.', + approvalOpeningMapApproval: '흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.', + approvalOpeningUnreadableFlow: '승인이 실행하는 흐름 {{flow}}을 읽을 수 없어 승인을 확인할 수 없습니다.', + approvalOpeningNoJobService: '{{object}}는 closedStates를 선언하지만 이 호스트는 job 서비스를 실행하지 않아, 아무도 끝내지 않는 승인을 종료할 수단이 없습니다. job 서비스를 설치하세요.', approvalSlaBreachedSubmitterTitle: '승인 요청이 기한을 넘겼습니다', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: 에스컬레이션 작업 '{{action}}'이(가) 실행되었습니다.", approvalApprovedTitle: '요청 승인됨', @@ -901,6 +1106,10 @@ export const koMessages: ApprovalMessages = { approvalReassignedBody: '이제 {{object}} {{record}}의 승인자입니다.', approvalAutoRejectedTitle: '승인이 자동 반려되었습니다', approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', + approvalAbandonedTitle: '승인이 완료되지 않았습니다', + approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', + approvalFlowNotContinuedTitle: '승인 흐름이 끝까지 진행되었는지 확인할 수 없습니다', + approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 끝까지 진행되었는지 확인할 수 없어 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 실행이 끝났거나 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', diff --git a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts index c2b46cb3ee0..48536977db7 100644 --- a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts @@ -117,6 +117,14 @@ export const ptBRObjects: NonNullable = { label: "Execução do registro", help: "Execução de automação que carrega o registro desta solicitação." }, + between_steps_json: { + label: "Entre etapas", + help: "Nós do fluxo que ficam entre duas etapas da aprovação à qual esta solicitação pertence." + }, + unjudged_since: { + label: "Não avaliada desde", + help: "Quando esta solicitação foi decidida, enquanto o que segue a decisão ainda não foi avaliado." + }, node_config_json: { label: "Configuração do nó", help: "Instantâneo da configuração do nó de aprovação (aprovadores/comportamento) para solicitações conduzidas por nó." diff --git a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts index b6cabc06994..37e4895ac26 100644 --- a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts @@ -117,6 +117,14 @@ export const ruObjects: NonNullable = { label: "Запуск записи", help: "Запуск автоматизации, который несёт запись этого запроса." }, + between_steps_json: { + label: "Между шагами", + help: "Узлы потока, стоящие между двумя шагами согласования, к которому относится этот запрос." + }, + unjudged_since: { + label: "Не оценено с", + help: "Когда по этому запросу было принято решение, пока то, что следует за решением, ещё не оценено." + }, node_config_json: { label: "Конфигурация узла", help: "Снимок конфигурации узла согласования (согласующие/поведение) для запросов, запускаемых узлом." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts index 09fdcc49087..34a3c318b97 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts @@ -117,6 +117,14 @@ export const zhCNObjects: NonNullable = { label: "记录运行", help: "承载此请求所在记录的自动化运行。" }, + between_steps_json: { + label: "步骤之间", + help: "审批中位于两个步骤之间的流程节点。" + }, + unjudged_since: { + label: "待判定起始时间", + help: "此请求被决定的时间;在此决定之后的流程尚未判定时记录。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts index 16384bf84d7..2b4c6bb8517 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts @@ -117,6 +117,14 @@ export const zhHantObjects: NonNullable = { label: "記錄執行", help: "承載此請求所在記錄的自動化執行。" }, + between_steps_json: { + label: "步驟之間", + help: "審批中位於兩個步驟之間的流程節點。" + }, + unjudged_since: { + label: "待判定起始時間", + help: "此請求被決定的時間;在此決定之後的流程尚未判定時記錄。" + }, node_config_json: { label: "節點設定", help: "由節點驅動之請求的核准節點設定(核准人/行為)快照。" diff --git a/packages/qa/dogfood/test/closed-state-lock.test.ts b/packages/qa/dogfood/test/closed-state-lock.test.ts new file mode 100644 index 00000000000..37469233b22 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-lock.test.ts @@ -0,0 +1,614 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D2 to D7, D10] The closed-state lock, on a real store. + * + * An object declares `closedStates`; a record whose stored state is one of + * the listed values is closed, and so are its direct `master_detail` lines. + * Every write a system context does not make is bound: an update, a delete, a + * line create, update, delete or move is refused `409 RECORD_LOCKED`, and a + * many-row write is refused whole before any row is written. + * + * Run on SQLite (`SqlDriver`, better-sqlite3 `:memory:`) in two store shapes, + * each pinned on its own: + * + * - **probe**: the store compiles the composed `ReadableIds` semi-join leaf, + * so a predicate write on lines is judged by one existence statement; + * - **no probe**: the same store declaring `readableIdsLeaf: false` (the + * MongoDB and OData shape), so a predicate write on lines is judged from + * the write's one read of its matched rows, under the engine's per-row + * ceiling. + * + * The cascade's "removes no row" is pinned on a store with transactions and + * on one that declares `transactionsUnsupported`. + * + * Ground truth is read through knex, past every engine layer. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { MAX_BULK_PER_ROW_HOOK_ROWS } from '@objectstack/spec/data'; +import { SysRecycleBin } from '@objectstack/platform-objects/system'; +import { SysUser } from '@objectstack/platform-objects/identity'; +import { changeRecordsOwner, transferUserAssignedWork } from '@objectstack/core'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { isSystem: true, userId: 'usr_system' } as const; +const CALLER = { userId: 'usr_caller', tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [] } as const; + +const CUSTOMER = 'dg_cs_customer'; +const CONTACT = 'dg_cs_contact'; +const INVOICE = 'dg_cs_invoice'; +const LINE = 'dg_cs_line'; +const BUDGET = 'dg_cs_budget'; +const ALLOC = 'dg_cs_alloc'; +const PAYMENT = 'dg_cs_payment'; + +const STATUS_OPTIONS = ['draft', 'sent', 'paid', 'void'].map((v) => ({ label: v, value: v })); + +const OBJECTS = [ + { name: CUSTOMER, label: 'Customer', fields: { name: { type: 'text', label: 'Name' } } }, + { name: CONTACT, label: 'Contact', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: INVOICE, + label: 'Invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + amount: { type: 'number', label: 'Amount' }, + customer: { type: 'lookup', label: 'Customer', reference: CUSTOMER, deleteBehavior: 'cascade' }, + contact: { type: 'lookup', label: 'Contact', reference: CONTACT }, + }, + closedStates: { status: ['paid', 'void'] }, + }, + { + name: LINE, + label: 'Invoice line', + fields: { + name: { type: 'text', label: 'Description' }, + qty: { type: 'number', label: 'Quantity' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + }, + }, + { + name: BUDGET, + label: 'Budget', + fields: { + name: { type: 'text', label: 'Name' }, + state: { type: 'select', label: 'State', options: [{ label: 'Open', value: 'open' }, { label: 'Frozen', value: 'frozen' }] }, + }, + closedStates: { state: ['frozen'] }, + }, + { + // A junction under two masters: a line of both (D3). + name: ALLOC, + label: 'Allocation', + fields: { + name: { type: 'text', label: 'Name' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + budget: { type: 'master_detail', label: 'Budget', reference: BUDGET, required: true }, + }, + }, +]; + +interface Shape { readonly probe: boolean; readonly transactions: boolean } + +let engine: ObjectQL; +let driver: SqlDriver; + +/** + * A payment is a LOOKUP child of the invoice, not a line: the lock does not + * bind it, and the invoice rolls its payments up into a summary field, so a + * payment write reaches the invoice through the engine's own recompute. + */ +const PAYMENT_OBJECT = { + name: PAYMENT, + label: 'Payment', + fields: { + name: { type: 'text', label: 'Reference' }, + paid: { type: 'number', label: 'Paid' }, + invoice: { type: 'lookup', label: 'Invoice', reference: INVOICE }, + }, +}; +const withPaymentSummary = (objects: typeof OBJECTS): unknown[] => [ + ...objects.map((o) => (o.name === INVOICE + ? { ...o, fields: { ...o.fields, paid_total: { type: 'summary', label: 'Paid total', summaryOperations: { object: PAYMENT, field: 'paid', function: 'sum' } } } } + : o)), + PAYMENT_OBJECT, +]; + +async function boot(shape: Shape, extra: { recycleBin?: boolean; users?: boolean; summary?: boolean } = {}): Promise { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + const supports = (driver as unknown as { supports: Record }).supports; + Object.defineProperty(driver, 'supports', { + configurable: true, + value: { ...supports, readableIdsLeaf: shape.probe, ...(shape.transactions ? {} : { transactionsUnsupported: true }) }, + }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-lock', + name: 'Closed-state lock', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [...(extra.summary ? withPaymentSummary(OBJECTS) : OBJECTS), ...(extra.recycleBin ? [SysRecycleBin] : []), ...(extra.users ? [SysUser] : [])], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + await engine.insert(CUSTOMER, { id: 'cu1', name: 'Acme' }, { context: SYS } as never); + await engine.insert(CONTACT, { id: 'ct1', name: 'Ada' }, { context: SYS } as never); + for (const [id, status] of [['inv_open', 'draft'], ['inv_open2', 'sent'], ['inv_paid', 'paid'], ['inv_void', 'void']] as const) { + await engine.insert(INVOICE, { id, name: id, status, amount: 10, customer: 'cu1', contact: 'ct1' }, { context: SYS } as never); + } + for (const [id, invoice] of [['l_open', 'inv_open'], ['l_open2', 'inv_open2'], ['l_paid', 'inv_paid'], ['l_paid2', 'inv_paid']] as const) { + await engine.insert(LINE, { id, name: id, qty: 1, invoice }, { context: SYS } as never); + } + await engine.insert(BUDGET, { id: 'b_open', name: 'Open', state: 'open' }, { context: SYS } as never); + await engine.insert(BUDGET, { id: 'b_frozen', name: 'Frozen', state: 'frozen' }, { context: SYS } as never); + await engine.insert(ALLOC, { id: 'a_open', name: 'a', invoice: 'inv_open', budget: 'b_open' }, { context: SYS } as never); + await engine.insert(ALLOC, { id: 'a_frozen', name: 'b', invoice: 'inv_open', budget: 'b_frozen' }, { context: SYS } as never); +} + +afterEach(async () => { + await engine?.destroy(); +}); + +type Knex = (table: string) => { select: (...c: string[]) => Promise>> }; +const knex = (): Knex => (driver as unknown as { knex: Knex }).knex; + +/** The table as stored: `id:col` for each row, sorted. */ +async function stored(table: string, col: string): Promise { + const rows = await knex()(table).select('id', col); + return rows.map((r) => `${r.id}:${r[col]}`).sort(); +} + +async function refusal(run: () => Promise): Promise<{ code?: unknown; status?: unknown; reason?: unknown; blockingObject?: unknown; message?: unknown }> { + try { + await run(); + } catch (e) { + return e as never; + } + throw new Error('expected the write to be refused, and it landed'); +} + +const by = (context: unknown) => ({ context }) as never; +const multi = (where: unknown, context: unknown = CALLER) => ({ where, multi: true, context }) as never; + +const SHAPES: ReadonlyArray = [ + ['a store that runs the probe', { probe: true, transactions: true }], + ['a store that cannot run the line probe', { probe: false, transactions: true }], +]; + +for (const [label, shape] of SHAPES) { + describe(`[ADR-0162 D4] the closed-state lock on ${label}`, () => { + // ── the record itself ────────────────────────────────────────────────── + it('a closed record refuses a by-id update, whichever field it carries; an open one takes it (control)', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 99 }, by(CALLER))); + expect([err.code, err.status, err.reason]).toEqual(['RECORD_LOCKED', 409, 'record_closed']); + await engine.update(INVOICE, { id: 'inv_open', amount: 99 }, by(CALLER)); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:10', 'inv_open:99', 'inv_paid:10', 'inv_void:10']); + }); + + it('the state field is frozen with the rest: a caller cannot reopen a closed record', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_void', status: 'draft' }, by(CALLER))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(INVOICE, 'status')).toContain('inv_void:void'); + }); + + it('an update that carries no field writes nothing and is not refused', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_paid' }, by(CALLER)); + }); + + it('a closed record refuses a by-id delete, and stays', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: CALLER } as never)); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'record_closed']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); + + it('a predicate update that reaches one closed record is refused whole; no row changes', async () => { + await boot(shape); + const err = await refusal(() => engine.update(INVOICE, { amount: 7 }, multi({ amount: 10 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'record_closed']); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:10', 'inv_open:10', 'inv_paid:10', 'inv_void:10']); + // control: a predicate that reaches only open records lands. + await engine.update(INVOICE, { amount: 7 }, multi({ status: { $in: ['draft', 'sent'] } })); + expect(await stored(INVOICE, 'amount')).toEqual(['inv_open2:7', 'inv_open:7', 'inv_paid:10', 'inv_void:10']); + }); + + it('a predicate delete that reaches one closed record is refused whole; no row is removed', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(INVOICE, multi({ customer: 'cu1' }))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(INVOICE, 'status')).toHaveLength(4); + }); + + it('a create of a record in a closed state is not judged (no stored state yet)', async () => { + await boot(shape); + await engine.insert(INVOICE, { id: 'inv_born_paid', name: 'x', status: 'paid', amount: 1 }, by(CALLER)); + expect(await stored(INVOICE, 'status')).toContain('inv_born_paid:paid'); + }); + + // ── a line of the record ────────────────────────────────────────────── + it('a line create under a closed master is refused; under an open one it lands (control)', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, { name: 'n', qty: 1, invoice: 'inv_paid' }, by(CALLER))); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'master_closed', INVOICE]); + await engine.insert(LINE, { id: 'l_new', name: 'n', qty: 1, invoice: 'inv_open' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_new:inv_open'); + }); + + it('a many-row create of lines is refused whole when one row names a closed master', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, [ + { id: 'l_a', name: 'a', qty: 1, invoice: 'inv_open' }, + { id: 'l_b', name: 'b', qty: 1, invoice: 'inv_void' }, + ], by(CALLER))); + expect(err.code).toBe('RECORD_LOCKED'); + expect(await stored(LINE, 'invoice')).toEqual(['l_open2:inv_open2', 'l_open:inv_open', 'l_paid2:inv_paid', 'l_paid:inv_paid']); + }); + + it('a line of a closed record refuses an update and a delete', async () => { + await boot(shape); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 5 }, by(CALLER)))).reason).toBe('master_closed'); + expect((await refusal(() => engine.delete(LINE, { where: { id: 'l_paid' }, context: CALLER } as never))).reason).toBe('master_closed'); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:1', 'l_open:1', 'l_paid2:1', 'l_paid:1']); + }); + + it('a move is refused at either end: out of a closed master, and into one; open to open lands', async () => { + await boot(shape); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', invoice: 'inv_open' }, by(CALLER)))).reason).toBe('master_closed'); + expect((await refusal(() => engine.update(LINE, { id: 'l_open', invoice: 'inv_paid' }, by(CALLER)))).reason).toBe('master_closed'); + await engine.update(LINE, { id: 'l_open', invoice: 'inv_open2' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open2'); + }); + + it('a predicate update of lines that reaches one line of a closed record is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { qty: 3 }, multi({ qty: 1 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'master_closed']); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:1', 'l_open:1', 'l_paid2:1', 'l_paid:1']); + // control: lines of open records only. + await engine.update(LINE, { qty: 3 }, multi({ invoice: { $in: ['inv_open', 'inv_open2'] } })); + expect(await stored(LINE, 'qty')).toEqual(['l_open2:3', 'l_open:3', 'l_paid2:1', 'l_paid:1']); + }); + + it('a predicate delete of lines that reaches one line of a closed record is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(LINE, multi({ qty: 1 }))); + expect(err.reason).toBe('master_closed'); + expect(await stored(LINE, 'qty')).toHaveLength(4); + }); + + it('a predicate update that moves open lines into a closed master is refused', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { invoice: 'inv_paid' }, multi({ invoice: 'inv_open' }))); + expect(err.reason).toBe('master_closed'); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); + + it('a junction row is a line of both masters: closed when either is', async () => { + await boot(shape); + // a_frozen hangs under an open invoice and a frozen budget. + expect((await refusal(() => engine.update(ALLOC, { id: 'a_frozen', name: 'z' }, by(CALLER)))).blockingObject).toBe(BUDGET); + await engine.update(ALLOC, { id: 'a_open', name: 'z' }, by(CALLER)); + expect((await refusal(() => engine.update(ALLOC, { name: 'y' }, multi({ invoice: 'inv_open' })))).blockingObject).toBe(BUDGET); + }); + + it('a predicate move out of a closed master is refused whole', async () => { + await boot(shape); + const err = await refusal(() => engine.update(LINE, { invoice: 'inv_open' }, multi({ invoice: 'inv_paid' }))); + expect(err.reason).toBe('master_closed'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toHaveLength(2); + }); + + it('a many-row create of records in a closed state is not judged', async () => { + await boot(shape); + await engine.insert(INVOICE, [ + { id: 'inv_b1', name: 'b1', status: 'paid', amount: 1 }, + { id: 'inv_b2', name: 'b2', status: 'void', amount: 1 }, + ], by(CALLER)); + expect(await stored(INVOICE, 'status')).toEqual(expect.arrayContaining(['inv_b1:paid', 'inv_b2:void'])); + }); + + it('a refused write runs no before-phase hook (D10)', async () => { + await boot(shape); + const ran: string[] = []; + engine.registerHook('beforeUpdate', async (ctx: { object: string }) => { ran.push(ctx.object); }, { object: [INVOICE, LINE] } as never); + engine.registerHook('beforeDelete', async (ctx: { object: string }) => { ran.push(ctx.object); }, { object: [INVOICE, LINE] } as never); + await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 1 }, by(CALLER))); + await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 1 }, by(CALLER))); + await refusal(() => engine.update(LINE, { qty: 2 }, multi({ qty: 1 }))); + await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: CALLER } as never)); + await refusal(() => engine.delete(LINE, multi({ qty: 1 }))); + expect(ran).toEqual([]); + await engine.update(INVOICE, { id: 'inv_open', amount: 1 }, by(CALLER)); + expect(ran).toEqual([INVOICE]); + }); + + it(`a predicate line write is judged ${shape.probe ? 'by one statement on the line table' : 'from the matched rows and one read of their masters'}`, async () => { + await boot(shape); + const seen: string[] = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + seen.push(object); + return find(object as never, ast as never, opts as never); + }) as typeof find; + await engine.update(LINE, { qty: 8 }, multi({ invoice: 'inv_open' })); + if (shape.probe) { + expect(seen.filter((o) => o === INVOICE)).toEqual([]); + expect(seen.filter((o) => o === LINE)).toHaveLength(1); + } else { + expect(seen.filter((o) => o === LINE)).toHaveLength(1); + expect(seen.filter((o) => o === INVOICE)).toHaveLength(1); + } + }); + + // ── what cannot be judged (D4) ───────────────────────────────────────── + it('cannot judge: a line write that names its master by something that is not one id', async () => { + await boot(shape); + const err = await refusal(() => engine.insert(LINE, { name: 'n', qty: 1, invoice: { id: 'inv_open' } }, by(CALLER))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + }); + + it('cannot judge: a read of the state that fails', async () => { + await boot(shape); + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + // The lock's probe of the master carries the closed predicate in its where. + if (object === INVOICE && JSON.stringify((ast as { where?: unknown })?.where ?? null).includes('"paid"')) throw new Error('store unavailable'); + return find(object as never, ast as never, opts as never); + }) as typeof find; + const err = await refusal(() => engine.update(LINE, { id: 'l_open', qty: 9 }, by(CALLER))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + expect(await stored(LINE, 'qty')).toContain('l_open:1'); + }); + + // ── the write that closes, and who is bound (D4 ▲, D5) ───────────────── + it('a write that closes an open record lands whole with its other fields; the next write is refused', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_open', status: 'paid', amount: 42 }, by(CALLER)); + expect(await stored(INVOICE, 'amount')).toContain('inv_open:42'); + expect(await stored(INVOICE, 'status')).toContain('inv_open:paid'); + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_open', amount: 43 }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + expect((await refusal(() => engine.insert(LINE, { name: 'late', qty: 1, invoice: 'inv_open' }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + }); + + it('a write with no principal (no context at all) is refused', async () => { + await boot(shape); + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 1 }))).code).toBe('RECORD_LOCKED'); + expect((await refusal(() => engine.update(LINE, { id: 'l_paid', qty: 2 }))).code).toBe('RECORD_LOCKED'); + }); + + it('a system context writes and deletes a closed record and its lines', async () => { + await boot(shape); + await engine.update(INVOICE, { id: 'inv_paid', amount: 5 }, by(SYS)); + await engine.update(LINE, { id: 'l_paid', qty: 5 }, by(SYS)); + await engine.update(LINE, { qty: 6 }, multi({ invoice: 'inv_paid' }, SYS)); + await engine.insert(LINE, { id: 'l_sys', name: 's', qty: 1, invoice: 'inv_paid' }, by(SYS)); + await engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: SYS } as never); + expect(await stored(INVOICE, 'status')).not.toContain('inv_paid:paid'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toEqual([]); + }); + + // ── the delete's cascade (D6) and the referential clear (D7) ─────────── + it('a delete whose cascade reaches a closed record removes no row, and names the object in the way', async () => { + await boot(shape); + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'cascade_reaches_closed', INVOICE]); + expect(await stored(CUSTOMER, 'name')).toEqual(['cu1:Acme']); + expect(await stored(INVOICE, 'status')).toHaveLength(4); + expect(await stored(LINE, 'qty')).toHaveLength(4); + // a system context deletes, its cascade with it. + await engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: SYS } as never); + expect(await stored(INVOICE, 'status')).toEqual([]); + }); + + it(`a cascade that reaches a line of a closed record is refused, ${shape.probe ? 'by one probe on the line table' : 'from the lines\' keys and one probe of their masters'}`, async () => { + await boot(shape); + const seen: Array<{ object: string; where: string; fields: unknown }> = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + const a = ast as { where?: unknown; fields?: unknown }; + seen.push({ object, where: JSON.stringify(a.where ?? null), fields: a.fields }); + return find(object as never, ast as never, opts as never); + }) as typeof find; + // inv_open is open; its cascade reaches a_frozen, a line of the frozen budget. + const err = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_open' }, context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'cascade_reaches_closed', BUDGET]); + expect(await stored(INVOICE, 'status')).toContain('inv_open:draft'); + expect(await stored(ALLOC, 'budget')).toEqual(['a_frozen:b_frozen', 'a_open:b_open']); + const budgetReads = seen.filter((r) => r.object === BUDGET); + if (shape.probe) { + expect(budgetReads).toEqual([]); + } else { + // The masters are asked of the store: the closed predicate rides the + // probe's where, and only the id comes back. + expect(budgetReads).toHaveLength(1); + expect(budgetReads[0].where).toContain('frozen'); + expect(budgetReads[0].fields).toEqual(['id']); + } + }); + + it('a referential clear lands on a closed record: exactly the cleared field', async () => { + await boot(shape); + await engine.delete(CONTACT, { where: { id: 'ct1' }, context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toEqual(['inv_open2:null', 'inv_open:null', 'inv_paid:null', 'inv_void:null']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); + }); +} + +describe('[ADR-0162 D4] the per-row ceiling on a store that cannot run the line probe', () => { + const seedLines = async (count: number) => { + const rows = Array.from({ length: count }, (_, i) => ({ + id: `bulk_${i}`, name: 'bulk', qty: 4, invoice: 'inv_open', organization_id: DEFAULT_ORGANIZATION_ID, + })); + const k = (driver as unknown as { knex: (t: string) => { insert: (r: unknown[]) => Promise } }).knex; + for (let i = 0; i < rows.length; i += 400) await k(LINE).insert(rows.slice(i, i + 400)); + }; + + it('a predicate line write whose matched rows pass the ceiling cannot be judged, and is refused', async () => { + await boot({ probe: false, transactions: true }); + await seedLines(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + const err = await refusal(() => engine.update(LINE, { qty: 5 }, multi({ qty: 4 }))); + expect([err.code, err.reason]).toEqual(['RECORD_LOCKED', 'cannot_judge']); + expect(String(err.message)).toContain(String(MAX_BULK_PER_ROW_HOOK_ROWS)); + }, 60_000); + + it('CONTROL: the same write on a store that runs the probe is judged by one statement and lands', async () => { + await boot({ probe: true, transactions: true }); + await seedLines(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + await engine.update(LINE, { qty: 5 }, multi({ qty: 4 })); + const rows = await knex()(LINE).select('id', 'qty'); + expect(rows.filter((r) => r.qty === 5)).toHaveLength(MAX_BULK_PER_ROW_HOOK_ROWS + 1); + }, 60_000); +}); + +describe('[ADR-0162 D6] a refused cascade removes no row, with and without transactions', () => { + for (const transactions of [true, false]) { + it(`on a store ${transactions ? 'with' : 'without'} transactions`, async () => { + await boot({ probe: true, transactions }); + const before = [await stored(CUSTOMER, 'name'), await stored(INVOICE, 'status'), await stored(LINE, 'qty')]; + expect((await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: CALLER } as never))).reason).toBe('cascade_reaches_closed'); + expect([await stored(CUSTOMER, 'name'), await stored(INVOICE, 'status'), await stored(LINE, 'qty')]).toEqual(before); + }); + } +}); + +describe('[ADR-0162 D7] restore', () => { + const entryFor = async (object: string, id: string): Promise => { + const rows = await knex()('sys_recycle_bin').select('id', 'object_name', 'record_id'); + const hit = rows.find((r) => r.object_name === object && r.record_id === id); + if (!hit) throw new Error(`no recycle-bin entry for ${object}/${id}`); + return String(hit.id); + }; + + it('refuses to put a line back under a live closed master that is not part of the entry; a system context restores', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: CALLER } as never); + await engine.update(INVOICE, { id: 'inv_open', status: 'paid' }, by(CALLER)); + const entry = await entryFor(LINE, 'l_open'); + const err = await refusal(() => engine.restore(entry, { context: CALLER } as never)); + expect([err.code, err.reason, err.blockingObject]).toEqual(['RECORD_LOCKED', 'master_closed', INVOICE]); + expect(await stored(LINE, 'invoice')).not.toContain('l_open:inv_open'); + await engine.restore(entry, { context: SYS } as never); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); + + it('an entry comes back as it stood, closed or not: a closed record restored with its lines', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(INVOICE, { where: { id: 'inv_paid' }, context: SYS } as never); + const entry = await entryFor(INVOICE, 'inv_paid'); + await engine.restore(entry, { context: SYS } as never); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + expect((await stored(LINE, 'invoice')).filter((r) => r.endsWith(':inv_paid'))).toHaveLength(2); + }); + + it('CONTROL: a line restored under an open master lands for the caller', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: CALLER } as never); + await engine.restore(await entryFor(LINE, 'l_open'), { context: CALLER } as never); + expect(await stored(LINE, 'invoice')).toContain('l_open:inv_open'); + }); +}); + +describe('[ADR-0162 D5] engine-derived writes that reach a closed record', () => { + it('the summary recompute writes the closed invoice in a system context, and lands', async () => { + await boot({ probe: true, transactions: true }, { summary: true }); + // The caller writes a payment (a lookup child, not a line): the write is + // free, and the roll-up onto inv_paid is the engine's own write. + await engine.insert(PAYMENT, { id: 'p1', name: 'p1', paid: 7, invoice: 'inv_paid' }, by(CALLER)); + expect(await stored(INVOICE, 'paid_total')).toContain('inv_paid:7'); + // The caller's own write of that field on the closed invoice is still refused. + expect((await refusal(() => engine.update(INVOICE, { id: 'inv_paid', amount: 11 }, by(CALLER)))).code).toBe('RECORD_LOCKED'); + }); + + it('the recycle-bin relink puts a cleared reference back on a closed record, for the caller', async () => { + await boot({ probe: true, transactions: true }, { recycleBin: true }); + await engine.delete(CONTACT, { where: { id: 'ct1' }, context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toContain('inv_paid:null'); + const rows = await knex()('sys_recycle_bin').select('id', 'object_name', 'record_id'); + const entry = rows.find((r) => r.object_name === CONTACT && r.record_id === 'ct1'); + await engine.restore(String(entry?.id), { context: CALLER } as never); + expect(await stored(INVOICE, 'contact')).toEqual(['inv_open2:ct1', 'inv_open:ct1', 'inv_paid:ct1', 'inv_void:ct1']); + expect(await stored(INVOICE, 'status')).toContain('inv_paid:paid'); + }); +}); + +describe('[ADR-0162 D10] free when not declared, and a master the write names', () => { + it('an object that neither declares the key nor is a line of one reads nothing extra', async () => { + await boot({ probe: true, transactions: true }); + const seen: string[] = []; + const find = driver.find.bind(driver); + (driver as unknown as { find: typeof find }).find = (async (object: string, ast: unknown, opts: unknown) => { + seen.push(object); + return find(object as never, ast as never, opts as never); + }) as typeof find; + await engine.update(CUSTOMER, { id: 'cu1', name: 'Acme 2' }, by(CALLER)); + await engine.update(CUSTOMER, { name: 'Acme 3' }, multi({ id: 'cu1' })); + expect(seen.filter((o) => o === INVOICE || o === BUDGET)).toEqual([]); + }); + + it('a master a beforeInsert hook supplies is not judged by the lock (the lock runs before the hooks)', async () => { + await boot({ probe: true, transactions: true }); + engine.registerHook('beforeInsert', (async (ctx: { input: { data: Record } }) => { + if (ctx.input.data.name === 'hooked') ctx.input.data.invoice = 'inv_paid'; + }) as never, { object: LINE } as never); + await engine.insert(LINE, { id: 'l_hooked', name: 'hooked', qty: 1, invoice: 'inv_open' }, by(CALLER)); + expect(await stored(LINE, 'invoice')).toContain('l_hooked:inv_paid'); + }); +}); + +describe('[ADR-0162 D7] Change Owner and the hand-over of a user\'s work are bound like any edit', () => { + const seedUsers = async () => { + for (const id of ['usr_a', 'usr_b']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@example.com` }, { context: SYS } as never); + } + for (const id of ['inv_open', 'inv_paid', 'inv_void']) await engine.update(INVOICE, { id, owner_id: 'usr_a' }, by(SYS)); + for (const id of ['l_open', 'l_paid']) await engine.update(LINE, { id, owner_id: 'usr_a' }, by(SYS)); + }; + + it('the bulk form moves the open records and lists each closed one among its failures, with RECORD_LOCKED', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, INVOICE, ['inv_open', 'inv_paid', 'inv_void'], { ownerId: 'usr_b' }, CALLER); + expect(report.updated).toBe(1); + expect(report.failed).toBe(2); + expect(report.failures.map((f: { id: unknown; code?: unknown }) => [f.id, f.code])).toEqual([ + ['inv_paid', 'RECORD_LOCKED'], + ['inv_void', 'RECORD_LOCKED'], + ]); + expect(await stored(INVOICE, 'owner_id')).toEqual(['inv_open2:null', 'inv_open:usr_b', 'inv_paid:usr_a', 'inv_void:usr_a']); + }); + + it('a line of a closed record keeps its owner the same way', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, LINE, ['l_open', 'l_paid'], { ownerId: 'usr_b' }, CALLER); + expect(report.failures.map((f: { id: unknown; code?: unknown }) => [f.id, f.code])).toEqual([['l_paid', 'RECORD_LOCKED']]); + }); + + it('the hand-over of a user\'s work leaves the closed records with that user and counts them among the failures', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await transferUserAssignedWork(engine as never, 'usr_a', 'usr_b', CALLER, { objects: [INVOICE] }); + const invoice = report.objects.find((o: { object: string }) => o.object === INVOICE)!; + expect([invoice.updated, invoice.failed]).toEqual([1, 2]); + expect(invoice.failures.every((f: { code?: unknown }) => f.code === 'RECORD_LOCKED')).toBe(true); + expect(await stored(INVOICE, 'owner_id')).toEqual(['inv_open2:null', 'inv_open:usr_b', 'inv_paid:usr_a', 'inv_void:usr_a']); + }); + + it('CONTROL: a system context changes the owner of a closed record', async () => { + await boot({ probe: true, transactions: true }, { users: true }); + await seedUsers(); + const report = await changeRecordsOwner(engine as never, INVOICE, ['inv_paid'], { ownerId: 'usr_b' }, SYS); + expect([report.updated, report.failed]).toEqual([1, 0]); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts new file mode 100644 index 00000000000..b1921b351f4 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-security-source.test.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's title on a real kernel, by what the + * kernel registers under `security`. `ObjectQLPlugin` hands the engine the + * service as a source (`SECURITY_SERVICE_SOURCE_SLOT`) and, beside it, a + * probe that answers whether a `security` service is registered at all, + * read without building one (`SECURITY_SERVICE_REGISTERED_SLOT`). Only the + * refusal's title rule reads the probe. + * + * - No `security` service registered: there is no field-level security, so + * the refusal names the title D8 gives. The rules on which field a title + * is read from still apply first: a title field the generic read does not + * return (internal, credential) or whose value is not display text + * (reference, a field `closedStates` names) gives the label form there too. + * - A `security` service registered and not resolvable (a factory that + * throws, or one the sync accessor does not build): the label form. + * - Every other reader of the source answers as it did: the `ReadableIds` + * resolution and the search's queryable-field read, before and after a + * refusal, and the probe builds no factory-registered service. + * + * Real `ObjectKernel`, `ObjectQLPlugin`, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const WRITER = { userId: 'usr_writer', tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [] } as const; +const by = (context: unknown) => ({ context }) as never; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; +const TAG = 'dg_css_tag'; +const SLIP = 'dg_css_slip'; +const KINDS = [ + { key: 'plain', object: 'dg_css_plain', label: 'Memo', titleField: 'name', def: { type: 'text', label: 'Name' }, value: 'Northwind March' }, + { key: 'internal', object: 'dg_css_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_css_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_css_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_css_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, +] as const; +const PLAIN = KINDS[0]; +const WITHHELD = KINDS.slice(1); + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Refusal { code?: unknown; status?: unknown; message?: unknown; userMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(err.message).toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + return String(err.userMessage); +} + +/** A `security` service the sync accessor never builds: registered as a factory. */ +function securityFactoryPlugin(factory: () => unknown): Plugin { + return { + name: 'dg-closed-state-security-factory', + init: async (ctx: PluginContext) => { + ctx.registerServiceFactory('security', factory); + }, + } as Plugin; +} + +let kernel: ObjectKernel | undefined; +let ql: ObjectQL; + +afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + kernel = undefined; +}); + +async function boot(extra: Plugin[] = []): Promise { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as never); + await kernel.use(new ObjectQLPlugin()); + for (const plugin of extra) await kernel.use(plugin); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + ql.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-security-source', + name: 'Closed-state refusal security source', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await ql.syncSchemas(); + await installDefaultOrganization(ql as never); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + ql.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } +} + +/** Update, by-id delete and cascade-delete root of one kind, as the writer. */ +async function refusalsOf(k: (typeof KINDS)[number]): Promise<{ update: string; del: string; cascade: string }> { + const update = sentenceOf(await refusal(() => ql.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER)))); + const del = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never))); + const cascade = sentenceOf(await refusal(() => ql.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never))); + return { update, del, cascade }; +} + +const untitledOf = (k: (typeof KINDS)[number]) => ({ + update: fill(en.record_closed_untitled, { object: k.label }), + del: fill(en.record_closed_untitled, { object: k.label }), + cascade: fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' }), +}); + +/** What the engine's other readers of the security source answer now. */ +async function otherReaders(): Promise<{ readableIds: unknown; searchQueryable: unknown }> { + const engine = ql as unknown as { + resolveReadableIdsSecurity(): { kind: string; why?: string }; + resolveSearchQueryableFields(object: string, context: unknown): Promise; + }; + const resolution = engine.resolveReadableIdsSecurity(); + return { + readableIds: { kind: resolution.kind, threw: typeof resolution.why === 'string' && resolution.why.startsWith('resolving the "security" service threw') }, + searchQueryable: await engine.resolveSearchQueryableFields(PLAIN.object, WRITER), + }; +} + +const SOURCE_THREW = { readableIds: { kind: 'unusable', threw: true }, searchQueryable: undefined }; + +describe('[ADR-0162 D8] the closed-state refusal\'s title, by what the kernel registers under `security`', () => { + it('no `security` service registered: the refusal names the title, on update, delete and a cascade-delete root', async () => { + await boot(); + const { update, del, cascade } = await refusalsOf(PLAIN); + expect(update).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(del).toBe(fill(en.record_closed, { object: PLAIN.label, title: PLAIN.value })); + expect(cascade).toBe(fill(en.record_closed_delete_blocked, { object: PLAIN.label, title: PLAIN.value, blockingObject: 'Slip' })); + }); + + it.each(WITHHELD.map((k) => [k.key, k] as const))( + 'no `security` service registered, %s title field: the label form, the field rules applying first', + async (_key, k) => { + await boot(); + expect(await refusalsOf(k)).toEqual(untitledOf(k)); + }, + ); + + it('a `security` service registered as a factory that throws: the label form', async () => { + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); + + it('a `security` service registered as a factory the sync accessor does not build: the label form, and the refusal builds nothing', async () => { + let built = 0; + const svc = { + getReadFilter: async () => null, + canReadObject: async () => true, + getReadableFields: async () => ['id', 'name', 'status', 'note'], + getQueryableFields: async () => ['id', 'name', 'status', 'note'], + }; + await boot([securityFactoryPlugin(() => { built += 1; return svc; })]); + const before = { built, readers: await otherReaders() }; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + expect({ built, readers: await otherReaders() }).toEqual(before); + }); + + it('the other readers of the security source answer as before: no service registered, and one registered that throws', async () => { + await boot(); + expect(await otherReaders(), 'no service, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'no service, after a refusal').toEqual(SOURCE_THREW); + await kernel!.shutdown(); + kernel = undefined; + + await boot([securityFactoryPlugin(() => { throw new Error('the security service cannot be built on this host'); })]); + expect(await otherReaders(), 'a throwing factory, before a refusal').toEqual(SOURCE_THREW); + await refusalsOf(PLAIN); + expect(await otherReaders(), 'a throwing factory, after a refusal').toEqual(SOURCE_THREW); + }); + + it('a source that throws with no probe beside it names no title', async () => { + await boot(); + delete (ql as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceRegistered')]; + expect(await refusalsOf(PLAIN)).toEqual(untitledOf(PLAIN)); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts new file mode 100644 index 00000000000..f68088b001a --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts @@ -0,0 +1,418 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D8] The closed-state refusal's sentence, on a real engine and store. + * + * The lock refuses `409 RECORD_LOCKED`; what a person reads is the Operation + * Message Catalog's sentence, carried as the refusal's `userMessage` and as its + * `message` behind the code. This file pins which form each refusal takes and + * what each may name, on `ObjectQL` over SQLite (`SqlDriver`, better-sqlite3 + * `:memory:`): + * + * - a record's own write: the title the writer would be served, by the + * security service's answer in the engine's slot (here a stand-in that + * answers per writer; the real plugin is booted in + * `closed-state-refusal-wire.dogfood.test.ts`): readable and not masked + * gives the title, unreadable or masked gives the label form; + * - a predicate write: the label form; + * - a line write and a line's restore: the master's label alone; + * - a delete refused for what it would also remove: the record asked to be + * deleted and the object in the way, the title only for one record; + * - an object with no label: the forms that name no label; never its API name; + * - a refusal that could not judge the write keeps the developer's sentence + * and marks no `userMessage`. + * + * Every person-facing string is checked for the absence of every API name, + * record id and state value of the fixture. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SysRecycleBin } from '@objectstack/platform-objects/system'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { isSystem: true, userId: 'usr_system' } as const; +const caller = (userId: string, locale?: string) => + ({ userId, tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [], ...(locale ? { locale } : {}) }) as const; +/** May read every field. */ +const WRITER = caller('usr_writer'); +/** May not read the invoice's or the customer's title field. */ +const UNREAD = caller('usr_unread'); +/** Is served the invoice's title field masked: readable, not queryable. */ +const MASKED = caller('usr_masked'); + +/** The slot `ObjectQLPlugin` fills with the registered `security` service's source. */ +const SECURITY_SLOT = Symbol.for('objectstack.objectql.securityServiceSource'); + +const INVOICE = 'dg_csr_invoice'; +const LINE = 'dg_csr_line'; +const CUSTOMER = 'dg_csr_customer'; +const PRODUCT = 'dg_csr_product'; +const BARE = 'dg_csr_bare'; + +const STATUS_OPTIONS = [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }]; + +const OBJECTS = [ + { name: CUSTOMER, label: 'Customer', fields: { name: { type: 'text', label: 'Name' } } }, + { name: PRODUCT, label: 'Product', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: INVOICE, + label: 'Invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + amount: { type: 'number', label: 'Amount' }, + customer: { type: 'lookup', label: 'Customer', reference: CUSTOMER, deleteBehavior: 'cascade' }, + }, + closedStates: { status: ['settled'] }, + }, + { + name: LINE, + label: 'Invoice line', + fields: { + name: { type: 'text', label: 'Description' }, + qty: { type: 'number', label: 'Quantity' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: INVOICE, required: true }, + product: { type: 'lookup', label: 'Product', reference: PRODUCT, deleteBehavior: 'cascade' }, + }, + }, + { + // No label: the sentence names no label, and never the API name. + name: BARE, + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + }, + closedStates: { status: ['settled'] }, + }, +]; + +/** Synthetic titles and ids. */ +const T = { closed: 'Northwind March', open: 'Fabrikam April', customer: 'Contoso Holdings', bare: 'Litware Group' } as const; +const IDS = ['cu1', 'cu2', 'cu3', 'pr1', 'inv_closed', 'inv_open', 'inv_other', 'l_closed', 'l_open', 'bare_closed']; + +let engine: ObjectQL; + +/** A stand-in for the security service's two field answers, per writer. */ +function fieldSecurity() { + const asked: Array<{ object: string; userId: unknown }> = []; + const titleFields = new Set([`${INVOICE}.name`, `${CUSTOMER}.name`]); + const all = (object: string) => Object.keys((OBJECTS.find((o) => o.name === object)?.fields ?? {}) as object).concat('id'); + return { + asked, + svc: { + async getReadableFields(object: string, context?: { userId?: unknown }) { + asked.push({ object, userId: context?.userId }); + return all(object).filter((f) => !(context?.userId === UNREAD.userId && titleFields.has(`${object}.${f}`))); + }, + async getQueryableFields(object: string, context?: { userId?: unknown }) { + return all(object).filter((f) => !((context?.userId === UNREAD.userId || context?.userId === MASKED.userId) && titleFields.has(`${object}.${f}`))); + }, + }, + }; +} + +async function boot(opts: { security?: unknown; recycleBin?: boolean; source?: () => unknown } = {}): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-sentence', + name: 'Closed-state refusal sentence', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [...OBJECTS, ...(opts.recycleBin ? [SysRecycleBin] : [])], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + const put = (object: string, row: Record) => engine.insert(object, row, { context: SYS } as never); + await put(CUSTOMER, { id: 'cu1', name: T.customer }); + await put(CUSTOMER, { id: 'cu2', name: 'Adventure Works' }); + await put(CUSTOMER, { id: 'cu3', name: 'Tailspin' }); + await put(PRODUCT, { id: 'pr1', name: 'Widget' }); + await put(INVOICE, { id: 'inv_closed', name: T.closed, status: 'settled', amount: 10, customer: 'cu1' }); + await put(INVOICE, { id: 'inv_open', name: T.open, status: 'draft', amount: 10, customer: 'cu2' }); + await put(INVOICE, { id: 'inv_other', name: 'Other', status: 'settled', amount: 10, customer: 'cu3' }); + await put(LINE, { id: 'l_closed', name: 'Widgets', qty: 1, invoice: 'inv_closed', product: 'pr1' }); + await put(LINE, { id: 'l_open', name: 'Gadgets', qty: 1, invoice: 'inv_open' }); + await put(BARE, { id: 'bare_closed', name: T.bare, status: 'settled' }); + if (opts.security !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = () => opts.security; + if (opts.source !== undefined) (engine as unknown as Record)[SECURITY_SLOT] = opts.source; +} + +afterEach(async () => { + await engine?.destroy(); +}); + +interface Refusal { code?: unknown; status?: unknown; reason?: unknown; message?: unknown; userMessage?: unknown; developerMessage?: unknown } + +async function refusal(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected the write to be refused, and it landed'); +} + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record = {}) => template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); +const FORBIDDEN = [INVOICE, LINE, CUSTOMER, PRODUCT, BARE, 'dg_csr', 'settled', 'closedStates', ...IDS]; + +/** The sentence a person reads, checked for the code and for every value it must not carry. */ +function sentenceOf(err: Refusal): string { + expect([err.code, err.status]).toEqual(['RECORD_LOCKED', 409]); + expect(typeof err.userMessage).toBe('string'); + expect(err.message, 'message carries the same sentence behind the code').toBe(`RECORD_LOCKED: ${String(err.userMessage)}`); + for (const value of FORBIDDEN) expect(String(err.userMessage), `carries ${value}`).not.toContain(value); + return String(err.userMessage); +} + +const by = (context: unknown) => ({ context }) as never; + +describe('[ADR-0162 D8] the closed-state refusal names what the writer is served, and nothing else', () => { + it('a record\'s own write: the title when no field-level security is registered (a read serves every field)', async () => { + await boot(); + const update = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(update)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + const del = await refusal(() => engine.delete(INVOICE, { where: { id: 'inv_closed' }, context: WRITER } as never)); + expect(sentenceOf(del)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + + it('the title only where the writer may be served the field: readable and unmasked yes, unreadable or masked no', async () => { + const { svc, asked } = fieldSecurity(); + await boot({ security: svc }); + const served = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(served)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + for (const writer of [UNREAD, MASKED]) { + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(writer))); + const sentence = sentenceOf(err); + expect(sentence, writer.userId).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence, writer.userId).not.toContain(T.closed); + } + // Asked as the writer, with the writer's own context. + expect(asked.map((a) => a.userId)).toEqual([WRITER.userId, UNREAD.userId, MASKED.userId]); + }); + + it('a security service that cannot say what is masked names no title (fail closed)', async () => { + await boot({ security: { getReadableFields: async () => ['id', 'name', 'status', 'amount', 'customer'] } }); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a security-service source that throws names no title; a source that answers null is no field-level security', async () => { + await boot({ source: () => { throw new Error('security service not resolvable'); } }); + const thrown = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(thrown)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + await engine.destroy(); + await boot({ source: () => null }); + const none = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + expect(sentenceOf(none)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closed })); + }); + + it('a predicate write names no one record: the label form', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { amount: 1 }, { where: { amount: 10 }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line write names the master by its label alone: update, delete, create and move', async () => { + await boot(); + const master = fill(en.record_closed_untitled, { object: 'Invoice' }); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.delete(LINE, { where: { id: 'l_closed' }, context: WRITER } as never)))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.insert(LINE, { name: 'Extra', qty: 1, invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + expect(sentenceOf(await refusal(() => engine.update(LINE, { id: 'l_open', invoice: 'inv_closed' }, by(WRITER))))) + .toBe(master); + }); + + it('a delete refused for what it would also remove: the record asked, its title as served, and the object in the way', async () => { + const { svc } = fieldSecurity(); + await boot({ security: svc }); + // The closed record itself would go. + const writer = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + expect(writer.reason).toBe('cascade_reaches_closed'); + // The title only for a caller served it. + const unread = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: UNREAD } as never)); + expect(sentenceOf(unread)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + // A line of the closed record would go while the record stays: the master is the object in the way. + const line = await refusal(() => engine.delete(PRODUCT, { where: { id: 'pr1' }, context: WRITER } as never)); + expect(sentenceOf(line)).toBe(fill(en.record_closed_delete_blocked, { object: 'Product', title: 'Widget', blockingObject: 'Invoice' })); + }); + + it('a title read that fails on the refusal path is reported, and the refusal stands in the label form', async () => { + await boot(); + const driver = engine.getDriverForObject(CUSTOMER) as unknown as { find: (...a: unknown[]) => Promise }; + const find = driver.find.bind(driver); + driver.find = async (object: unknown, query: any, ...rest: unknown[]) => { + // Only the refusal's own title read: the record by id, its id and title column. + if (object === CUSTOMER && Array.isArray(query?.fields) && query.fields.join() === 'id,name' && query?.limit === 1) { + throw new Error('store unavailable'); + } + return find(object, query, ...rest); + }; + const warned: Array<[string, unknown]> = []; + const logger = (engine as unknown as { logger: { warn: (m: string, meta?: unknown) => void } }).logger; + const warn = logger.warn.bind(logger); + logger.warn = (m: string, meta?: unknown) => { warned.push([m, meta]); warn(m, meta); }; + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: 'cu1' }, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + expect(warned.filter(([m]) => m.startsWith('[closed-state] the title of')), 'the failed read is reported').toHaveLength(1); + expect((await engine.find(CUSTOMER, { where: { id: 'cu1' }, context: SYS } as never)).length, 'nothing was deleted').toBe(1); + }); + + it('a delete that names many records takes the label form', async () => { + await boot(); + const err = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1', 'cu3'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' })); + }); + + it('the cascade\'s title form reads the ids the delete named: a delete that names its rows by a predicate takes the label form, one row matched or many', async () => { + await boot(); + const untitled = fill(en.record_closed_delete_blocked_untitled, { object: 'Customer', blockingObject: 'Invoice' }); + const byTitle = await refusal(() => engine.delete(CUSTOMER, { where: { name: T.customer }, multi: true, context: WRITER } as never)); + expect(sentenceOf(byTitle)).toBe(untitled); + const oneOfIn = await refusal(() => engine.delete(CUSTOMER, { where: { id: { $in: ['cu1'] } }, multi: true, context: WRITER } as never)); + expect(sentenceOf(oneOfIn)).toBe(untitled); + }); + + it('an object with no label is never named by its API name', async () => { + await boot(); + expect(sentenceOf(await refusal(() => engine.update(BARE, { id: 'bare_closed', name: 'x' }, by(WRITER))))) + .toBe(fill(en.record_closed_unlabeled, { title: T.bare })); + expect(sentenceOf(await refusal(() => engine.update(BARE, { name: 'x' }, { where: { name: T.bare }, multi: true, context: WRITER } as never)))) + .toBe(en.record_closed_opaque); + }); + + it('answers in the caller\'s language', async () => { + await boot(); + const zh = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(caller('usr_writer', 'zh-CN')))); + expect(sentenceOf(zh)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closed })); + const es = await refusal(() => engine.update(LINE, { id: 'l_closed', qty: 2 }, by(caller('usr_writer', 'es')))); + expect(sentenceOf(es)).toBe(fill(BUILTIN_OPERATION_MESSAGES['es-ES'].record_closed_untitled, { object: 'Invoice' })); + }); + + it('a line\'s restore under a live closed master names the master by its label alone', async () => { + await boot({ recycleBin: true }); + await engine.delete(LINE, { where: { id: 'l_open' }, context: WRITER } as never); + await engine.update(INVOICE, { id: 'inv_open', status: 'settled' }, by(WRITER)); + const bin = (await engine.find('sys_recycle_bin', { context: SYS } as never)) as Array>; + const entry = bin.find((r) => r.object_name === LINE && r.record_id === 'l_open'); + expect(entry).toBeDefined(); + const err = await refusal(() => engine.restore(String(entry!.id), { context: WRITER } as never)); + expect(sentenceOf(err)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('the developer\'s sentence is kept on developerMessage; a refusal that could not judge keeps it as its message', async () => { + await boot(); + const err = await refusal(() => engine.update(INVOICE, { id: 'inv_closed', amount: 99 }, by(WRITER))); + sentenceOf(err); + expect(String(err.developerMessage)).toContain(`'${INVOICE}'`); + // A line write that names its master by something that is not one id cannot be judged. + const cannot = await refusal(() => engine.insert(LINE, { name: 'x', qty: 1, invoice: { $in: ['inv_closed'] } }, by(WRITER))); + expect([cannot.code, cannot.status, cannot.reason]).toEqual(['RECORD_LOCKED', 409, 'cannot_judge']); + expect(cannot.userMessage).toBeUndefined(); + expect(String(cannot.message)).toContain(LINE); + }); +}); + +/** + * [ADR-0162 D8] The title is named only from a field that holds display text + * and that the writer's generic read returns. Each object below declares its + * title field (`nameField`) as one that is not: a field the generic read + * withholds (`internal`; a credential type), a reference field, and the field + * the object's `closedStates` names. Each answers the label form on every path + * that reads a title: the record's update, its delete, and a delete whose + * cascade reaches a closed record (the root's title). + */ +describe('[ADR-0162 D8] the title comes only from a display-text field the generic read returns', () => { + const TAG = 'dg_csr_tag'; + const SLIP = 'dg_csr_slip'; + const KINDS = [ + { key: 'internal', object: 'dg_csr_internal', label: 'Ledger', titleField: 'code', def: { type: 'text', label: 'Code', internal: true }, value: 'LEDGER-CODE-7' }, + { key: 'credential', object: 'dg_csr_credential', label: 'Vault', titleField: 'passcode', def: { type: 'password', label: 'Passcode' }, value: 'PASSCODE-VALUE-7' }, + { key: 'reference', object: 'dg_csr_reference', label: 'Tagged', titleField: 'tag', def: { type: 'lookup', label: 'Tag', reference: TAG }, value: 'tag1' }, + { key: 'state', object: 'dg_csr_state', label: 'Stage', titleField: 'status', def: undefined, value: 'settled' }, + ] as const; + + async function bootKinds(): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + const kindObjects = KINDS.map((k) => ({ + name: k.object, + label: k.label, + nameField: k.titleField, + fields: { + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + note: { type: 'text', label: 'Note' }, + ...(k.def ? { [k.titleField]: k.def } : {}), + }, + closedStates: { status: ['settled'] }, + })); + const slip = { + name: SLIP, + label: 'Slip', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + ...Object.fromEntries(KINDS.map((k) => [`${k.key}_ref`, { type: 'lookup', label: k.label, reference: k.object, deleteBehavior: 'cascade' }])), + }, + closedStates: { status: ['settled'] }, + }; + engine.registerApp({ + id: 'com.objectstack.dogfood.closed-state-refusal-title-fields', + name: 'Closed-state refusal title fields', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [{ name: TAG, label: 'Tag', fields: { name: { type: 'text', label: 'Name' } } }, ...kindObjects, slip], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + // Seeded through the driver: the rows are data at rest, whatever a write of each field type would do. + const put = (object: string, row: Record) => + engine.getDriverForObject(object)!.create(object, { organization_id: DEFAULT_ORGANIZATION_ID, ...row }); + await put(TAG, { id: 'tag1', name: 'Priority' }); + for (const k of KINDS) { + const title = k.key === 'state' ? {} : { [k.titleField]: k.value }; + await put(k.object, { id: `${k.key}_closed`, status: 'settled', ...title }); + await put(k.object, { id: `${k.key}_root`, status: 'draft', ...(k.key === 'state' ? {} : title) }); + await put(SLIP, { id: `slip_${k.key}`, name: `Slip ${k.key}`, status: 'settled', [`${k.key}_ref`]: `${k.key}_root` }); + } + } + + const ALL_VALUES = KINDS.map((k) => k.value).filter((v) => v !== 'settled'); + + it.each(KINDS.map((k) => [k.key, k] as const))('%s title field: the label form on update, delete and a cascade-delete root', async (_key, k) => { + await bootKinds(); + const untitled = fill(en.record_closed_untitled, { object: k.label }); + const update = await refusal(() => engine.update(k.object, { id: `${k.key}_closed`, note: 'x' }, by(WRITER))); + expect(sentenceOf(update), 'update').toBe(untitled); + const del = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_closed` }, context: WRITER } as never)); + expect(sentenceOf(del), 'delete').toBe(untitled); + const cascade = await refusal(() => engine.delete(k.object, { where: { id: `${k.key}_root` }, context: WRITER } as never)); + expect(sentenceOf(cascade), 'cascade-delete root').toBe(fill(en.record_closed_delete_blocked_untitled, { object: k.label, blockingObject: 'Slip' })); + for (const err of [update, del, cascade]) { + for (const value of [...ALL_VALUES, `${k.key}_closed`, `${k.key}_root`, 'Priority']) { + expect(String(err.userMessage), value).not.toContain(value); + } + } + }); + + it('control: the same objects with a display-text title field name the title', async () => { + await bootKinds(); + // The slip's own title field is `name`, display text the generic read returns. + const err = await refusal(() => engine.update(SLIP, { id: 'slip_internal', name: 'renamed' }, by(WRITER))); + expect(sentenceOf(err)).toBe(fill(en.record_closed, { object: 'Slip', title: 'Slip internal' })); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts new file mode 100644 index 00000000000..2094e1948cb --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts @@ -0,0 +1,330 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0162 D8, D10] The closed-state refusal on the wire, on a real boot. +// +// ## The composition +// +// `bootStack` with the real `SecurityPlugin`, `ObjectQL`, SQL driver, REST and +// auth layers. Three synthetic objects: an invoice that closes at `settled`, +// its `master_detail` line, and a customer whose delete cascades to its +// invoices. A fourth, a private note that closes at `done`, carries the +// row-access case. Every row is written through the doors by the principals +// below, so each carries its organization and owner as a real write does. +// +// Principals, by permission set: +// +// - the writer: create, read, edit and delete on every object; +// - the withheld writer: the same, with the invoice's title field +// `readable: false` (field-level security); +// - the reader: read only on the invoice (the object permission refuses an +// edit), and edit on the note it does not own (row access refuses it). +// +// ## What is asserted, by class +// +// - The person-facing member: a refused write carries `userMessage`, the +// catalog's sentence in the caller's language, and the wire's `error` reads +// the same sentence. Neither names an API name, a record id or a state value. +// - The title is the one the writer would be served (D8): the titled form for +// the writer, the label form for the withheld writer, whose read of the same +// record does not carry the title field (the control that the field is +// really withheld). +// - A line write names the master by its label alone (D8). +// - A delete refused for what it would also remove names the record asked to +// be deleted and the label of the object in the way (D6, D8). Its untitled +// form is pinned at the engine (closed-state-refusal-sentence.test.ts). +// - D10 at the security layer: a caller the object permission or the row +// access refuses gets the same answer on a closed record as on an open one, +// status and body. +// +// What the wire relays of the refusal's other members is measured and pinned +// too: the developer sentence (API names) stays off the wire, and so do the +// lock's own `reason` / `lockReason` members (D8: nothing machine-readable in +// the refusal names the producer). + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const INVOICE = 'csr_invoice'; +const LINE = 'csr_line'; +const CUSTOMER = 'csr_customer'; +const NOTE = 'csr_note'; +const SYS = { context: { isSystem: true } } as const; + +/** Synthetic titles: words no sentence of the catalog contains. */ +const T = { + closedInvoice: 'Northwind March', + openInvoice: 'Fabrikam April', + customer: 'Contoso Holdings', + otherCustomer: 'Litware Group', +} as const; + +const Invoice = ObjectSchema.create({ + name: INVOICE, + label: 'Invoice', + pluralLabel: 'Invoices', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Number', required: true }), + status: Field.select({ label: 'Status', options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }), + amount: Field.number({ label: 'Amount' }), + customer: Field.lookup(CUSTOMER, { label: 'Customer', deleteBehavior: 'cascade' }), + }, + closedStates: { status: ['settled'] }, +}); + +const Line = ObjectSchema.create({ + name: LINE, + label: 'Invoice line', + pluralLabel: 'Invoice lines', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Description', required: true }), + qty: Field.number({ label: 'Quantity' }), + invoice: Field.masterDetail(INVOICE, { label: 'Invoice', required: true }), + }, +}); + +const Customer = ObjectSchema.create({ + name: CUSTOMER, + label: 'Customer', + pluralLabel: 'Customers', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const Note = ObjectSchema.create({ + name: NOTE, + label: 'Note', + pluralLabel: 'Notes', + sharingModel: 'private', + fields: { + name: Field.text({ label: 'Subject', required: true }), + state: Field.select({ label: 'State', options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }), + }, + closedStates: { state: ['done'] }, +}); + +const fixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.closed-state-refusal', + namespace: 'csr', + version: '0.0.0', + type: 'app', + name: 'Closed-state refusal fixture', + description: 'An invoice that closes, its lines, a customer that cascades to it, and a private note that closes.', + }, + objects: [Invoice, Line, Customer, Note], +}); + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const; +const writerSet = PermissionSetSchema.parse({ + name: 'csr_writer', + label: 'Closed-state writer', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, +}); +const withheldSet = PermissionSetSchema.parse({ + name: 'csr_withheld', + label: 'Closed-state writer, invoice title withheld', + objects: { [INVOICE]: FULL, [LINE]: FULL, [CUSTOMER]: FULL, [NOTE]: FULL }, + fields: { + [`${INVOICE}.name`]: { readable: false, editable: false }, + }, +}); +const readerSet = PermissionSetSchema.parse({ + name: 'csr_reader', + label: 'Closed-state reader', + objects: { + [INVOICE]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [NOTE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }, + }, +}); + +const PRINCIPALS = { writer: writerSet.name, withheld: withheldSet.name, reader: readerSet.name } as const; +type Who = keyof typeof PRINCIPALS; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +interface Answer { + status: number; + body: Record; +} + +describe('[ADR-0162 D8, D10] the closed-state refusal on the wire', () => { + let stack: VerifyStack; + let ql: any; + const token: Record = {} as never; + const id: Record = {}; + /** Every value a person-facing string must not carry: API names, ids, state values. */ + const forbidden = (): string[] => [INVOICE, LINE, CUSTOMER, NOTE, 'csr_', 'settled', 'closedStates', ...Object.values(id)]; + + const call = async (who: Who | 'admin', method: string, path: string, body?: unknown, locale?: string): Promise => { + const res = await stack.api(path, { + method, + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token[who]}`, + ...(locale ? { 'Accept-Language': locale } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const text = await res.text(); + return { status: res.status, body: text ? JSON.parse(text) : {} }; + }; + const created = async (who: Who | 'admin', object: string, body: Record): Promise => { + const a = await call(who, 'POST', `/data/${object}`, body); + expect(a.status, JSON.stringify(a.body)).toBe(201); + return String(a.body?.id ?? a.body?.record?.id ?? ''); + }; + /** The two person-facing strings of a refusal, and what neither may carry. */ + const personFacing = (a: Answer): string => { + expect(a.status, JSON.stringify(a.body)).toBe(409); + expect(a.body.code).toBe('RECORD_LOCKED'); + expect(typeof a.body.userMessage, JSON.stringify(a.body)).toBe('string'); + expect(a.body.error, 'the wire\'s `error` reads the same sentence').toBe(a.body.userMessage); + for (const value of forbidden()) { + expect(a.body.userMessage, `userMessage carries ${value}`).not.toContain(value); + expect(a.body.error, `error carries ${value}`).not.toContain(value); + } + return a.body.userMessage as string; + }; + + beforeAll(async () => { + stack = await bootStack(fixtureStack as unknown as Parameters[0], { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, writerSet, withheldSet, readerSet], + fallbackPermissionSet: readerSet.name, + }), + }); + ql = await stack.kernel.getServiceAsync('objectql'); + const idOf = async (email: string) => + String((await ql.findOne('sys_user', { where: { email }, context: { isSystem: true } }))?.id ?? ''); + token.admin = await stack.signIn(); + for (const who of Object.keys(PRINCIPALS) as Who[]) { + const email = `csr-${who}@verify.test`; + token[who] = await stack.signUp(email); + const userId = await idOf(email); + id[`${who}User`] = userId; + expect(await catalogPermissionSet(ql, PRINCIPALS[who]), PRINCIPALS[who]).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: userId, permission_set: PRINCIPALS[who] }, SYS); + } + + // Every row through the doors. Lines are added while their invoice is + // open; the closing write lands whole (D4) and closes it. + id.customer = await created('writer', CUSTOMER, { name: T.customer }); + id.otherCustomer = await created('writer', CUSTOMER, { name: T.otherCustomer }); + id.closedInvoice = await created('writer', INVOICE, { name: T.closedInvoice, status: 'draft', amount: 10, customer: id.customer }); + id.openInvoice = await created('writer', INVOICE, { name: T.openInvoice, status: 'draft', amount: 10, customer: id.otherCustomer }); + id.closedLine = await created('writer', LINE, { name: 'Widgets', qty: 1, invoice: id.closedInvoice }); + id.openLine = await created('writer', LINE, { name: 'Gadgets', qty: 1, invoice: id.openInvoice }); + const closing = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { status: 'settled', amount: 12 }); + expect(closing.status, JSON.stringify(closing.body)).toBe(200); + // Notes owned by the administrator: private to the reader, who may edit the object. + id.closedNote = await created('admin', NOTE, { name: 'Quarter close', state: 'open' }); + id.openNote = await created('admin', NOTE, { name: 'Quarter plan', state: 'open' }); + expect((await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { state: 'done' })).status).toBe(200); + + // The scene is real: the withheld writer is served the invoice without + // its title field, the writer with it. + const read = async (who: Who) => (await call(who, 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).body; + const withheld = read('withheld'); + const writer = read('writer'); + const w = (await withheld).record ?? (await withheld); + const v = (await writer).record ?? (await writer); + expect('name' in w, 'the withheld writer is served no title field').toBe(false); + expect(v.name).toBe(T.closedInvoice); + }, 180_000); + + afterAll(async () => { + if (stack) await stack.stop(); + }); + + it('an update of a closed record names it by the title the writer is served, in userMessage and error alike', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a writer whose field permissions withhold the title field is told the label form, never the stored title', async () => { + const a = await call('withheld', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + const sentence = personFacing(a); + expect(sentence).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + expect(sentence).not.toContain(T.closedInvoice); + }); + + it('a delete of a closed record answers the same sentence family', async () => { + const a = await call('writer', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + expect(personFacing(a)).toBe(fill(en.record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('a line write names the master by its label alone: an update in place, and a new line', async () => { + const update = await call('writer', 'PATCH', `/data/${LINE}/${id.closedLine}`, { qty: 5 }); + expect(personFacing(update)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + const create = await call('writer', 'POST', `/data/${LINE}`, { name: 'Extra', qty: 1, invoice: id.closedInvoice }); + expect(personFacing(create)).toBe(fill(en.record_closed_untitled, { object: 'Invoice' })); + }); + + it('a delete refused for what it would also remove names the record asked to be deleted and the object in the way', async () => { + const writer = await call('writer', 'DELETE', `/data/${CUSTOMER}/${id.customer}`); + expect(personFacing(writer)).toBe(fill(en.record_closed_delete_blocked, { object: 'Customer', title: T.customer, blockingObject: 'Invoice' })); + // The untitled form (root title not served) is pinned at the engine in + // closed-state-refusal-sentence.test.ts: on this wire a writer whose + // field permissions withhold the customer's title field is refused the + // delete of its own customer by the security layer before the engine is + // reached (reported out of scope). + // Nothing was removed. + expect((await call('writer', 'GET', `/data/${INVOICE}/${id.closedInvoice}`)).status).toBe(200); + expect((await call('writer', 'GET', `/data/${CUSTOMER}/${id.customer}`)).status).toBe(200); + }); + + it('answers in the caller\'s language', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }, 'zh-CN'); + expect(personFacing(a)).toBe(fill(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed, { object: 'Invoice', title: T.closedInvoice })); + }); + + it('relays neither the developer sentence nor the lock\'s own members', async () => { + const a = await call('writer', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 99 }); + personFacing(a); + const wire = JSON.stringify(a.body); + expect(wire).not.toContain('closedStates'); + expect(a.body).not.toHaveProperty('developerMessage'); + expect(a.body).not.toHaveProperty('reason'); + expect(a.body).not.toHaveProperty('lockReason'); + expect(a.body).not.toHaveProperty('blockingObject'); + }); + + it('D10: a caller the object permission refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${INVOICE}/${id.closedInvoice}`, { amount: 1 }); + const open = await call('reader', 'PATCH', `/data/${INVOICE}/${id.openInvoice}`, { amount: 1 }); + expect(closed.status).toBe(403); + expect(closed.body.code).toBe('PERMISSION_DENIED'); + expect(closed).toEqual(open); + const closedDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.closedInvoice}`); + const openDelete = await call('reader', 'DELETE', `/data/${INVOICE}/${id.openInvoice}`); + expect(closedDelete.status).toBe(403); + expect(closedDelete).toEqual(openDelete); + }); + + it('D10: a caller the row access refuses gets the same answer on a closed record as on an open one', async () => { + const closed = await call('reader', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + const open = await call('reader', 'PATCH', `/data/${NOTE}/${id.openNote}`, { name: 'x' }); + expect(closed.status).not.toBe(409); + expect(closed.body.code).not.toBe('RECORD_LOCKED'); + // The two answers differ only by the id the caller addressed, where the body echoes it. + expect(JSON.stringify(closed).split(id.closedNote).join('ID')).toBe(JSON.stringify(open).split(id.openNote).join('ID')); + const closedDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.closedNote}`); + const openDelete = await call('reader', 'DELETE', `/data/${NOTE}/${id.openNote}`); + expect(closedDelete.status).not.toBe(409); + expect(JSON.stringify(closedDelete).split(id.closedNote).join('ID')).toBe(JSON.stringify(openDelete).split(id.openNote).join('ID')); + // CONTROL: the owner is told the note is closed. + const owner = await call('admin', 'PATCH', `/data/${NOTE}/${id.closedNote}`, { name: 'x' }); + expect(owner.status).toBe(409); + expect(owner.body.code).toBe('RECORD_LOCKED'); + }); +}); diff --git a/packages/qa/dogfood/test/closed-state-system-writes.test.ts b/packages/qa/dogfood/test/closed-state-system-writes.test.ts new file mode 100644 index 00000000000..947cafc0589 --- /dev/null +++ b/packages/qa/dogfood/test/closed-state-system-writes.test.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, D7] Two writes the platform makes on its own, measured against + * a record in a closed state: the approval status mirror and the assignment + * rules. Each was listed as a system write with no test of it. + * + * - The approval status mirror writes `pending` when an approval opens on a + * record and `approved` when it is decided. On a record already closed by + * another field, both writes land: they are system writes, which the lock + * does not bind (D5). The caller's own write of the same record, between + * and after, is refused `409 RECORD_LOCKED` with the closed-state sentence. + * - The assignment rules write no stored record at all: the engine evaluates + * them on a row it is inserting, before the write, and an update never + * evaluates a rule (`assignment-rules.ts`). A row inserted already in its + * closed state by a caller is routed to its owner and lands; nothing about + * the rule writes the record afterwards, and the caller's later write of + * it is refused. + * + * Real kernel, real ObjectQL engine with the closed-state lock, real + * automation engine and approval node, driver-sql on better-sqlite3 + * `:memory:`. The approval's record lock (`lockRecord`) is off, so the one + * lock a caller meets is the closed-state one. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { + ApprovalService, + registerApprovalNode, + SysApprovalRequest, + SysApprovalAction, + SysApprovalApprover, + SysApprovalDelegation, +} from '@objectstack/plugin-approvals'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, tenantId: ORG, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const platformObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email'), banned: { name: 'banned', type: 'boolean' as const } } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, +] as const; + +const INVOICE = 'dg_csw_invoice'; +const TICKET = 'dg_csw_ticket'; + +/** Closed by its own `status`; the approval mirrors onto another field. */ +const invoice = { + name: INVOICE, + label: 'Invoice', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Draft', value: 'draft' }, { label: 'Settled', value: 'settled' }] }, + approval_status: { name: 'approval_status', type: 'select' as const, options: ['draft', 'pending', 'approved', 'rejected'].map((value) => ({ label: value, value })) }, + }, + closedStates: { status: ['settled'] }, +}; +const ticket = { + name: TICKET, + label: 'Ticket', + fields: { + name: text('name'), + note: text('note'), + status: { name: 'status', type: 'select' as const, options: [{ label: 'Open', value: 'open' }, { label: 'Done', value: 'done' }] }, + }, + closedStates: { status: ['done'] }, +}; + +const review = { + name: 'csw_review', label: 'Review', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'review', type: 'approval', label: 'Review', config: { approvers: [{ type: 'user', value: 'approver' }], lockRecord: false, approvalStatusField: 'approval_status' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + ], +}; + +const en = BUILTIN_OPERATION_MESSAGES.en; +const fill = (template: string, params: Record) => + template.replace(/\{\{(\w+)\}\}/g, (m, k: string) => params[k] ?? m); + +describe('[ADR-0162 D5, D7] the platform\'s own writes on a record in a closed state', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, ticket, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation]) { + ql.registry.registerObject(def as any, 'closed-state-system-writes', 'closed-state-system-writes'); + } + for (const o of platformObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + (ql as any).registerApp({ + id: 'com.objectstack.dogfood.closed-state-system-writes', name: 'closed_state_system_writes', queues: [], + assignmentRules: [{ name: 'ticket_owner', object: TICKET, active: true, entries: [{ name: 'all', assignTo: { type: 'user', value: 'lead' } }] }], + }); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'lead']) { + await ql.insert('sys_user', { id, email: `${id}@example.test`, banned: false }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any, messaging: { emit: async () => {} } as any }); + // The host runs the plugin's sweeps, as one with a `job` service does: an + // approval on an object that declares `closedStates` does not open on a + // host that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + automation.registerFlow(review.name, review as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0] as any; + const pendingRequest = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id, status: 'pending' }, context: SYS }) as any[]).map((r) => String(r.id)); + /** + * The caller's own write, refused by the closed-state lock with its sentence. + * This kernel registers no `security` service, so there is no field-level + * security and the sentence names the record's title. + */ + async function expectCallerRefused(object: string, id: string, label: string, title: string): Promise { + let caught: any; + try { + await ql.update(object, { id, note: 'edited by hand' }, { context: asPerson('owner') }); + } catch (err) { + caught = err; + } + expect(caught, 'the caller\'s write is refused').toBeDefined(); + expect(caught.code).toBe('RECORD_LOCKED'); + expect(caught.status ?? caught.statusCode).toBe(409); + expect(caught.userMessage).toBe(fill(en.record_closed, { object: label, title })); + expect((await read(object, id)).note ?? null, 'nothing of the refused write landed').toBeNull(); + } + + it('the approval status mirror\'s `pending` and `approved` land on a record closed by another field; the caller\'s write is refused between and after', async () => { + await ql.insert(INVOICE, { id: 'inv1', name: 'Northwind March', status: 'settled', approval_status: 'draft', organization_id: ORG }, { context: { ...SYS, tenantId: ORG } }); + + const run = (await automation.execute(review.name, { object: INVOICE, record: await read(INVOICE, 'inv1'), userId: 'owner' } as any)) as any; + expect(run.status, JSON.stringify(run)).toBe('paused'); + const opened = await read(INVOICE, 'inv1'); + expect(opened.approval_status, 'the mirror\'s `pending` landed on the closed record').toBe('pending'); + expect(opened.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + + const [request] = await pendingRequest('inv1'); + expect(request).toBeTruthy(); + await svc.decide(request, { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')); + const decided = await read(INVOICE, 'inv1'); + expect(decided.approval_status, 'the mirror\'s `approved` landed on the closed record').toBe('approved'); + expect(decided.status).toBe('settled'); + await expectCallerRefused(INVOICE, 'inv1', 'Invoice', 'Northwind March'); + }); + + it('an assignment rule routes a row a caller inserts already closed, and the insert lands; the rule never writes it again, and the caller\'s write is refused', async () => { + const row = (await ql.insert(TICKET, { id: 't1', name: 'Quarter close', status: 'done', organization_id: ORG }, { context: asPerson('owner') })) as any; + expect(row.owner_id, 'the rule routed the row it was inserting').toBe('lead'); + expect((await read(TICKET, 't1')).owner_id).toBe('lead'); + await expectCallerRefused(TICKET, 't1', 'Ticket', 'Quarter close'); + expect((await read(TICKET, 't1')).owner_id, 'an update evaluates no rule').toBe('lead'); + }); +}); diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index e659821e3d3..fc6e792521d 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -1541,6 +1541,7 @@ function buildSandboxContext( const provenanceRaw = engineCtx?.provenance; const provenance = declaredStringMarks({ flowRunId: provenanceRaw?.flowRunId, + flowRootRunId: provenanceRaw?.flowRootRunId, attributedUserId: provenanceRaw?.attributedUserId, performedByClientId: provenanceRaw?.performedByClientId, performedByAgentId: provenanceRaw?.performedByAgentId, diff --git a/packages/runtime/src/sandbox/script-runner.ts b/packages/runtime/src/sandbox/script-runner.ts index 404db3f8b56..b30cb82f12f 100644 --- a/packages/runtime/src/sandbox/script-runner.ts +++ b/packages/runtime/src/sandbox/script-runner.ts @@ -275,7 +275,7 @@ export interface ScriptContext { * (`@objectstack/spec/data`), which objectql's `buildProvenance()` stamps from * the server-built execution context on every write assembly site. * - * Projected to the three declared members, each copied only in its declared + * Projected to the declared members, each copied only in its declared * shape (a string) and absent otherwise; the whole key is ABSENT when none * survives, which is what the engine face carries on a write with no origin * (a plain REST write). Read it as `ctx.provenance?.flowRunId`. @@ -290,6 +290,7 @@ export interface ScriptContext { */ provenance?: { flowRunId?: string; + flowRootRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; diff --git a/packages/services/service-automation/src/builtin/map-node.ts b/packages/services/service-automation/src/builtin/map-node.ts index a6ab215e4c8..ea2fa6ae5f3 100644 --- a/packages/services/service-automation/src/builtin/map-node.ts +++ b/packages/services/service-automation/src/builtin/map-node.ts @@ -216,6 +216,13 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // (AutomationEngine.creditChildRun). A failed or refused item's answer // carries none. const itemDrops: unknown[] = []; + // [ADR-0162 Execution item 8] The item runs THIS entry started, in order, + // on every exit: the engine copies them onto this entry's step + // (`childRunIds`), where a reader of the parent's log finds each one. + // An item that started no run, and an item paused with no run id, add + // none. + const startedRuns: string[] = []; + const rolledRuns = (): { childRunIds?: string[] } => (startedRuns.length > 0 ? { childRunIds: [...startedRuns] } : {}); const rolledDrops = () => { const droppedFields = foldDropEvents(itemDrops); return droppedFields ? { droppedFields } : {}; @@ -260,6 +267,10 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v delete childContext.saveNotice; const child = await engine.execute(flowName, childContext); + // A child that ended inside the call answers no `runId`: the engine + // names the run it started for this context. + const childRunId = child.runId ?? engine.runStartedFor(childContext); + if (childRunId) startedRuns.push(String(childRunId)); if (child.status === 'paused') { if (!child.runId) { @@ -276,6 +287,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // back (AutomationEngine.creditChildRun). metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, ...rolledDrops(), + ...rolledRuns(), }; } if (!child.success) { @@ -306,6 +318,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // `try_catch` or `fault` edge that contains this failure lets the // run complete, and its answer folds this step. ...rolledDrops(), + ...rolledRuns(), }; } if (child.status === 'refused') { @@ -350,6 +363,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v : rolledFailures()), }, ...rolledDrops(), + ...rolledRuns(), }; } // Synchronous completion — record and advance. @@ -401,6 +415,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v output: { results: state.results, count: state.results.filter(r => !isMapItemCancelledMarker(r)).length }, metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, ...rolledDrops(), + ...rolledRuns(), }; }, }); diff --git a/packages/services/service-automation/src/builtin/subflow-node.ts b/packages/services/service-automation/src/builtin/subflow-node.ts index f74fd9c219e..26c93b7612d 100644 --- a/packages/services/service-automation/src/builtin/subflow-node.ts +++ b/packages/services/service-automation/src/builtin/subflow-node.ts @@ -123,6 +123,14 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext delete childContext.saveNotice; const child = await engine.execute(flowName, childContext); + // [ADR-0162 Execution item 8] The child run, on every exit below that + // has one: the engine copies it onto this node's step (`childRunIds`). + // A child that ended inside the call answers no `runId`: the engine + // names the run it started for this context. A child that started no + // run (missing, disabled, skipped by its start condition) and a pause + // with no run id name none. + const childRunId = child.runId ?? engine.runStartedFor(childContext); + const childRuns = childRunId ? { childRunIds: [String(childRunId)] } : {}; if (child.status === 'paused') { // Nested durable pause: the child's continuation is persisted under its @@ -138,6 +146,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext suspend: true, correlation: `subflow:${child.runId}`, screen: child.screen, + ...childRuns, }; } // #4354 — roll the child's totals up into this node's step. The child's @@ -177,6 +186,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext // (`inner-refusal.ts`); `{}` for a child that met none. ...carriedRefusalOfResult(child), ...(rolled ? { metrics: rolled } : {}), + ...childRuns, }; } @@ -209,6 +219,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext success: true as const, output: { output: child.output ?? null }, ...(metrics ? { metrics } : {}), + ...childRuns, // #32861 — the values the child's write steps did not store ride up // onto this step, so the parent's answer (`AutomationResult.droppedFields`) // tells the caller about a drop its delegated write met. Set by the diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 8e41a0b59a4..a091a2b3d12 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -24,7 +24,7 @@ import { summarizeRun } from './run-summary.js'; import { withDroppedFields } from './run-dropped-fields.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; // The values below (`AutomationEngine` for its public static -// `MAX_NODE_REENTRIES`, and `activeMsAtPause`) are read only inside the function bodies, at call time, +// `MAX_NODE_REENTRIES`, `activeMsAtPause` and `MAX_STEP_CHILD_RUN_IDS`) are read only inside the function bodies, at call time, // never while a module is evaluating, so the import cycle with ./engine.js is // safe under ESM live bindings; the tsup bundle is one file and has no cycle. import { @@ -36,6 +36,7 @@ import { FlowSuspendSignal, isRefusalSignal, isSuspendSignal, + MAX_STEP_CHILD_RUN_IDS, nestedChildRunId, type ExecutionLogEntry, type NodeExecutionResult, @@ -103,6 +104,26 @@ export function runUserOf(context: AutomationContext | undefined): EvalUserParse }); } +/** + * [ADR-0162 Execution item 8] The child runs a step started + * (`NodeExecutionResult.childRunIds`), copied onto the step: the non-empty + * strings only, the member omitted where none is left. Total, never throwing, + * for the reason {@link stepAdvisoriesOf} gives. + * + * [seat ruling 7258590209 on #37767] Bounded here, for every executor: the + * step names at most {@link MAX_STEP_CHILD_RUN_IDS} runs, the first ones + * started, and carries `childRunIdsTruncated: true` where there were more. + */ +function stepChildRunsOf(result: NodeExecutionResult): { childRunIds?: string[]; childRunIdsTruncated?: true } { + const raw: unknown = result.childRunIds; + if (!Array.isArray(raw)) return {}; + const ids = raw.filter((id): id is string => typeof id === 'string' && id.length > 0); + if (ids.length === 0) return {}; + return ids.length > MAX_STEP_CHILD_RUN_IDS + ? { childRunIds: ids.slice(0, MAX_STEP_CHILD_RUN_IDS), childRunIdsTruncated: true } + : { childRunIds: ids }; +} + /** * The step-log copy of an executor's advisory members, in exactly the shape * `ExecutionStepLogSchema` declares for them. The step is persisted with the @@ -179,6 +200,7 @@ export interface DagTraversalHost { readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; readonly describeDisabledFlow: AutomationEngine['describeDisabledFlow']; readonly nextRunId: AutomationEngine['nextRunId']; + readonly noteRunStarted: AutomationEngine['noteRunStarted']; readonly seedRunVariables: AutomationEngine['seedRunVariables']; readonly resolveRunContext: AutomationEngine['resolveRunContext']; readonly validateNodeInputSchemas: AutomationEngine['validateNodeInputSchemas']; @@ -496,6 +518,7 @@ export async function executeNode( error: { code: 'NODE_FAILURE', message: errMsg }, // In the declared step-log shape only (`stepAdvisoriesOf`). ...stepAdvisoriesOf(result), + ...stepChildRunsOf(result), // #4354 — a node that failed PART WAY may still have written // rows; dropping its counts would understate what the run did. ...(result.metrics ? { metrics: result.metrics } : {}), @@ -571,6 +594,7 @@ export async function executeNode( // (`dropEventsOf`). Both members are copied in the declared // step-log shape only (`stepAdvisoriesOf`). ...stepAdvisoriesOf(result), + ...stepChildRunsOf(result), ...(result.metrics ? { metrics: result.metrics } : {}), }); @@ -1355,7 +1379,7 @@ export function startConditionHolds( /** The body of {@link AutomationEngine.executeWithoutRetry}, moved unedited; that method's docblock is its contract. */ export async function executeWithoutRetry( - this: Pick, + this: Pick, flowName: string, context?: AutomationContext, dispatched?: { errorMessage: string | undefined }, @@ -1437,6 +1461,10 @@ export async function executeWithoutRetry( this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; } + // [ADR-0162 Execution item 8] Past the gate this attempt is a run + // that leaves a history row; the skip above records none, so it + // names no run ({@link AutomationEngine.runStartedFor}). + this.noteRunStarted(context, runId); // [#9889] The SAME definition-level guard attempt 1 runs under — // the sixth instance of this method drifting from `execute()` diff --git a/packages/services/service-automation/src/engine-residual-log-cause.test.ts b/packages/services/service-automation/src/engine-residual-log-cause.test.ts index 586167768bc..8fb8346939f 100644 --- a/packages/services/service-automation/src/engine-residual-log-cause.test.ts +++ b/packages/services/service-automation/src/engine-residual-log-cause.test.ts @@ -329,6 +329,55 @@ describe('#6499 sites 1–4 — SuspendedRunStore driver seams', () => { assertSilent(streams.stderr, 'durable run lookup failed', 'stderr'); }); + // [ADR-0162 Execution item 8] The strict read (`getRun(runId, { strict: true })`): + // the same two store reads, and the store's failure is the caller's answer + // instead of `null`. Each read rejects with the store's own error and logs + // its strict sentence once, as the default read logs its own above. + it('site 3, strict read: a throwing loadTerminal rejects, and the record says the failure is thrown', async () => { + const engine = new AutomationEngine(jsonLogger(), workingStore({ + async loadTerminal() { throw new Error(MULTILINE_DRIVER); }, + })); + + let thrown: unknown; + const streams = await captureBoth(async () => { + await engine.getRun('run_gone', { strict: true }).then( + () => { thrown = 'resolved'; }, + (err: unknown) => { thrown = err; }, + ); + }); + + expect(thrown, 'the store failure reaches the caller, not null').toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(MULTILINE_DRIVER); + const record = soleRecordWith(streams.stdout, 'durable run lookup failed'); + expectOneLineWithCause(record, 'warn'); + expect(record.msg).toContain('this strict read throws the failure to its caller'); + expect(record.msg).not.toContain('DEGRADES to null'); + assertSilent(streams.stderr, 'durable run lookup failed', 'stderr'); + }); + + it('site 3, strict read: a throwing paused-run load rejects, and the record says the failure is thrown', async () => { + const engine = new AutomationEngine(jsonLogger(), workingStore({ + async loadTerminal() { return null; }, + async load(): Promise { throw new Error(MULTILINE_DRIVER); }, + })); + + let thrown: unknown; + const streams = await captureBoth(async () => { + await engine.getRun('run_gone', { strict: true }).then( + () => { thrown = 'resolved'; }, + (err: unknown) => { thrown = err; }, + ); + }); + + expect(thrown, 'the store failure reaches the caller, not null').toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(MULTILINE_DRIVER); + const record = soleRecordWith(streams.stdout, 'durable paused-run lookup failed'); + expectOneLineWithCause(record, 'warn'); + expect(record.msg).toContain('this strict read throws the failure to its caller'); + expect(record.msg).not.toContain('DEGRADES to null'); + assertSilent(streams.stderr, 'durable paused-run lookup failed', 'stderr'); + }); + it("site 4: recordTerminal — #4632 DURABILITY, RAISED warn→error: the run reads healthy while its history row never landed", async () => { const engine = new AutomationEngine(jsonLogger(), workingStore({ async recordTerminal() { throw new Error(MULTILINE_DRIVER); }, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a178e793a41..cefe9541a99 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -472,6 +472,24 @@ export interface NodeExecutionResult { * approval request id). For observability / lookup; not required to resume. */ correlation?: string; + /** + * [ADR-0162 Execution item 8] The child runs this execution of the node + * started — a `subflow`'s one run, the item runs of a `map` — on every exit, + * paused, failed, refused or completed, where a run started and has an id + * (a child that paused with no run id names none). The engine copies them + * onto the step's {@link StepLogEntry} (`childRunIds`), so a reader of the + * run's log reaches each child run without the parent's context: at most + * {@link MAX_STEP_CHILD_RUN_IDS} of them, the first ones started, and + * `childRunIdsTruncated` on the step where this execution started more. + * Two bounds of the durable history can still leave a reader without a + * link. A log of more than {@link MAX_PERSISTED_HISTORY_STEPS} steps is + * compacted ({@link compactStepLogForHistory}), which can drop a step + * with its link. And a step log over the history row's byte cap has its + * links shed before any step is dropped, each step that named child runs + * marked `childRunIdsTruncated` (`serializeStepsBounded` in + * `suspended-run-store.ts`). + */ + childRunIds?: string[]; /** * Screen to render — set by a `screen` node that suspends to collect input. * Surfaced on the paused {@link AutomationResult} so a UI runner can render @@ -1010,6 +1028,19 @@ export const DEFAULT_MAX_EXECUTION_LOG_SIZE = 1000; */ export const MAX_PERSISTED_HISTORY_STEPS = 200; +/** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] Most child + * run ids one step names ({@link StepLogEntry.childRunIds}). A `map` starts + * up to its 10,000-item cap of item runs, and one run id is about 40 + * characters: named whole, one step could carry a run's step log past the + * history row's byte cap and cost the row the steps it keeps. A step whose + * execution started more names the first ones started and carries + * `childRunIdsTruncated: true`, so a reader never takes the list for all of + * them. The same number as the approvals plugin's cap on the runs it reads + * for one approval. + */ +export const MAX_STEP_CHILD_RUN_IDS = 200; + /** * Cap on the in-memory {@link AutomationEngine.consumedSuspensions} journal — * the hot half of the operator restore path (#13909). @@ -1175,6 +1206,23 @@ export interface StepLogEntry { * (`dropEventsOf`). */ droppedFields?: DroppedFieldsEvent[]; + /** + * [ADR-0162 Execution item 8] The child runs this step started + * ({@link NodeExecutionResult.childRunIds}), as `ExecutionStepLogSchema` + * declares the member: a `subflow`'s one run, the item runs of a `map`, + * at most {@link MAX_STEP_CHILD_RUN_IDS}. Absent where the step started + * none. + */ + childRunIds?: string[]; + /** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] `true` + * where this step started more child runs than `childRunIds` names: its + * execution started more than {@link MAX_STEP_CHILD_RUN_IDS}, or the + * history row shed the step's links to fit its byte cap (`childRunIds` + * is then absent). Absent where the list names every child run the step + * started. + */ + childRunIdsTruncated?: true; /** * #1479: structured-region grouping. When a step ran inside a `loop` / * `parallel` / `try_catch` body region, these tag it with its **immediate** @@ -3813,6 +3861,36 @@ export class AutomationEngine implements IAutomationService { return nextRunId(); } + /** + * [ADR-0162 Execution item 8] The run each context object handed to + * {@link execute} last started, keyed by that object. A run that completes, + * fails or refuses inside the call answers no `runId` (the contract sets it + * on a paused run only), so a delegating node that must record the child + * run it started asks {@link runStartedFor} with the context it passed. + * Weakly held: an entry lives as long as the caller keeps its context. + */ + private readonly runsStartedByContext = new WeakMap(); + + /** Note that `runId` was started for the caller's `context` ({@link runsStartedByContext}). */ + private noteRunStarted(context: AutomationContext | undefined, runId: string): void { + if (context && typeof context === 'object') this.runsStartedByContext.set(context, runId); + } + + /** + * [ADR-0162 Execution item 8] The id of the run the last {@link execute} + * call handed this very `context` object started, whatever it ended in; + * `undefined` where no run started (the flow was missing, disabled, had no + * start node, its start condition skipped it, or the re-entry guard did): + * a run is noted once it is past those gates, where it leaves a history + * row, or where it fails before its first node and is recorded as failed. + * Under `errorHandling.strategy: 'retry'` it is the last attempt that + * started a run. Read by the `subflow` and `map` nodes, which pass each + * child a context of its own. + */ + runStartedFor(context: AutomationContext): string | undefined { + return this.runsStartedByContext.get(context); + } + /** * Persist a suspended run to the in-memory cache and (best-effort) the * durable store. A store failure does not fail the run — the in-memory copy @@ -8015,7 +8093,15 @@ export class AutomationEngine implements IAutomationService { return suspendedRunToLogEntry(run); } - getRun(runId: string): Promise { + /** + * One run's log entry: the in-memory entry, else its terminal history row, + * else its suspension row; `null` where none answers. A store that fails + * is logged and read as `null` too, unless `options.strict` is set + * ([ADR-0162 Execution item 8]): then the store's failure is thrown, so a + * caller that decides on a missing run can tell a run with no row from a + * store that did not answer. + */ + getRun(runId: string, options?: { strict?: boolean }): Promise { // The body lives in ./run-history.ts (#25222). const readStore = () => this.store; const host: ThisParameterType = { @@ -8025,7 +8111,7 @@ export class AutomationEngine implements IAutomationService { logger: this.logger, suspendedRunToLogEntry: (...a) => this.suspendedRunToLogEntry(...a), }; - return getRun.call(host, runId); + return getRun.call(host, runId, options); } /** @@ -8389,6 +8475,9 @@ export class AutomationEngine implements IAutomationService { // and recorded as such, never a throw out of `execute()`. Any // other throw is unchanged. if (!(err instanceof HeldValueCycleError)) throw err; + // [ADR-0162 Execution item 8] A run that fails before its first + // node is recorded as a failed run: it started. + this.noteRunStarted(context, runId); return this.failRunBeforeFirstNode({ runId, flowName, flow, startedAt, startTime, context, error: err.message }); } stampFlowRunSlot(runContext, flowName, runPackage); @@ -8479,6 +8568,10 @@ export class AutomationEngine implements IAutomationService { this.activeRecordFlows.add(reentryKey); reentryHeld = true; } + // [ADR-0162 Execution item 8] Past both gates the run is dispatched + // and leaves a history row whatever it ends in. Neither skip above + // records one, so neither names a run here ({@link runStartedFor}). + this.noteRunStarted(context, runId); // Validate node input schemas before execution. [#9889] The same // call sits in `executeWithoutRetry` — every retry attempt must be @@ -12276,6 +12369,7 @@ export class AutomationEngine implements IAutomationService { isFlowEnabled: (...a) => this.isFlowEnabled(...a), describeDisabledFlow: (...a) => this.describeDisabledFlow(...a), nextRunId: (...a) => this.nextRunId(...a), + noteRunStarted: (...a) => this.noteRunStarted(...a), seedRunVariables: (...a) => this.seedRunVariables(...a), resolveRunContext: (...a) => this.resolveRunContext(...a), evaluateCondition: (...a) => this.evaluateCondition(...a), diff --git a/packages/services/service-automation/src/run-history.ts b/packages/services/service-automation/src/run-history.ts index b60e2baaf0e..79ee881efdb 100644 --- a/packages/services/service-automation/src/run-history.ts +++ b/packages/services/service-automation/src/run-history.ts @@ -317,7 +317,7 @@ export function suspendedRunToLogEntry(run: SuspendedRun): ExecutionLogEntry { } /** The body of {@link AutomationEngine.getRun}, moved unedited; that method's docblock is its contract. */ -export async function getRun(this: Pick, runId: string): Promise { +export async function getRun(this: Pick, runId: string, options?: { strict?: boolean }): Promise { // LAST entry wins, not the first: a run that pauses and later finishes // records TWO entries under the same run id ('paused', then // 'completed'/'failed'/'cancelled'). Scanning forwards returned the stale @@ -331,7 +331,8 @@ export async function getRun(this: Pick 0 ? context.locale : undefined; @@ -568,6 +582,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R : {}), ...(context.userId && caller === undefined && runPosture(context) ? { posture: runPosture(context) } : {}), ...(flowRunId ? { flowRunId } : {}), + ...(flowRootRunId ? { flowRootRunId } : {}), ...(locale ? { locale } : {}), ...(impersonatedBy ? { impersonatedBy } : {}), }); @@ -619,6 +634,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R if (runPrincipalKind(context)) out.principalKind = 'agent'; if (context.tenantId) out.tenantId = context.tenantId; if (flowRunId) out.flowRunId = flowRunId; + if (flowRootRunId) out.flowRootRunId = flowRootRunId; if (locale) out.locale = locale; if (impersonatedBy) out.impersonatedBy = impersonatedBy; return out; diff --git a/packages/services/service-automation/src/step-child-runs.test.ts b/packages/services/service-automation/src/step-child-runs.test.ts new file mode 100644 index 00000000000..6cae20b790f --- /dev/null +++ b/packages/services/service-automation/src/step-child-runs.test.ts @@ -0,0 +1,290 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0162 Execution item 8] A delegating step records the child runs it +// started (`childRunIds` on its step log entry): the one run of a `subflow`, +// on every exit, and for a `map` the item runs this execution of the step +// started, so a reader of one run's log can follow the link to every run of +// its tree. A child that ends inside the call answers no `runId`, so the +// engine names the run it started for the context it was handed +// (`runStartedFor`). A step names at most `MAX_STEP_CHILD_RUN_IDS` runs and +// says so where it started more (`childRunIdsTruncated`), and the history +// row sheds the links, marked, before it drops any step (seat ruling +// 7258590209). + +import { describe, it, expect, vi } from 'vitest'; +import { AutomationEngine, MAX_STEP_CHILD_RUN_IDS } from './engine.js'; +import { ObjectStoreSuspendedRunStore, type SuspendedRunStoreEngine } from './suspended-run-store.js'; +import { InMemoryFlowActivationStore } from './flow-activation-store.js'; +import { + registerSubflowNode, + registerMapNode, + registerWaitNode, + registerLogicNodes, +} from './builtin/index.js'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import type { ExecutionStepLog } from '@objectstack/spec/automation'; +import type { RunRecord, StepLogEntry } from './engine.js'; +import { withLoaderSetFromPull } from './loader-set.test-support.js'; +import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; + +function createTestLogger(): any { + const l: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + l.child = () => l; + return l; +} + +function rig(store?: ConstructorParameters[1]) { + const engine = withLoaderSetFromPull(new AutomationEngine(createTestLogger(), store)); + engine.setFlowActivationStore(new InMemoryFlowActivationStore()); + const ctx = { logger: createTestLogger(), getService: () => undefined } as any; + for (const register of [registerSubflowNode, registerMapNode, registerWaitNode, registerLogicNodes]) { + (register as (e: AutomationEngine, c: unknown) => void)(engine, ctx); + } + return engine; +} + +type Node = Record; +const START: Node = { id: 'start', type: 'start', label: 'Start', config: {} }; +const END: Node = { id: 'end', type: 'end', label: 'End' }; +const NOOP: Node = { id: 'noop', type: 'assignment', label: 'Nothing', config: {} }; +const WAIT: Node = { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }; +function chain(name: string, nodes: Node[]) { + return { + name, label: name, type: 'autolaunched', + nodes: [START, ...nodes, END], + edges: [START, ...nodes, END].slice(1).map((n, i, rest) => ({ + id: `e${i}`, source: (i === 0 ? START : rest[i - 1]).id as string, target: n.id as string, + })), + }; +} +const sub = (flowName: string, id = 'call'): Node => ({ id, type: 'subflow', label: 'Call', config: { flowName } }); +const map = (flowName: string, items: unknown[], id = 'each'): Node => ({ id, type: 'map', label: 'Each', config: { flowName, collection: items } }); + +// Type-level pin: the engine's exported step type declares the member the +// spec's step log declares, with the same type, so `getRun`'s answer is typed +// as the schema says. Compiled by the package's typecheck, invisible to vitest. +type Eq = (() => G extends A ? 1 : 2) extends () => G extends B ? 1 : 2 ? true : false; +type Assert = T; +export type _ChildRunIdsInStep = Assert< + Eq, Pick> +>; + +const stepOf = async (engine: AutomationEngine, runId: string, nodeId: string) => + ((await engine.getRun(runId)) as any)?.steps?.filter((s: any) => s.nodeId === nodeId) ?? []; + +describe('[ADR-0162 item 8] a delegating step records the child runs it started', () => { + it('a subflow whose child completes inside the call: the step names the child run', async () => { + const engine = rig(); + engine.registerFlow('child', chain('child', [NOOP]) as any); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + const context = {} as AutomationContext; + const out: any = await engine.execute('parent', context); + expect(out.success).toBe(true); + expect(out.runId, 'a completed run answers no runId').toBeUndefined(); + + const parentRun = engine.runStartedFor(context)!; + expect(parentRun).toBeTruthy(); + const [step] = await stepOf(engine, parentRun, 'call'); + expect(step.childRunIds).toHaveLength(1); + const child: any = await engine.getRun(step.childRunIds[0]); + expect(child?.flowName).toBe('child'); + expect(child?.status).toBe('completed'); + const [first] = await stepOf(engine, parentRun, 'start'); + expect(first.childRunIds, 'a step that started no run carries none').toBeUndefined(); + }); + + it('a subflow whose child pauses: the parked step names the run its pause correlates with', async () => { + const engine = rig(); + engine.registerFlow('child', chain('child', [WAIT]) as any); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + const out: any = await engine.execute('parent', {} as AutomationContext); + expect(out.status).toBe('paused'); + const [step] = await stepOf(engine, out.runId, 'call'); + const parked: any = await (engine as any).suspensionOf(out.runId); + expect(parked.correlation).toBe(`subflow:${step.childRunIds[0]}`); + }); + + it('a map: the step names every item run it started, each a run of its own', async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + engine.registerFlow('batch', chain('batch', [map('item', [1, 2, 3])]) as any); + const context = {} as AutomationContext; + const out: any = await engine.execute('batch', context); + expect(out.success).toBe(true); + const steps = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + const ids = steps.flatMap((s: any) => s.childRunIds ?? []); + expect(ids).toHaveLength(3); + expect(new Set(ids).size).toBe(3); + for (const id of ids) expect(((await engine.getRun(id)) as any)?.flowName).toBe('item'); + }); + + it('no run started: runStartedFor answers nothing for a flow that is not registered', async () => { + const engine = rig(); + const context = {} as AutomationContext; + const out: any = await engine.execute('missing', context); + expect(out.success).toBe(false); + expect(engine.runStartedFor(context)).toBeUndefined(); + }); + + it('no run started: a child its start condition skips is named by no step and by runStartedFor', async () => { + const engine = rig(); + const gated = chain('child', [NOOP]) as any; + gated.nodes = gated.nodes.map((n: Node) => (n.type === 'start' ? { ...n, config: { condition: '1 == 2' } } : n)); + engine.registerFlow('child', gated); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + + const direct = {} as AutomationContext; + const skipped: any = await engine.execute('child', direct); + expect(skipped.output).toEqual({ skipped: true, reason: 'condition_not_met' }); + expect(engine.runStartedFor(direct), 'a skipped start leaves no history row, so it names no run').toBeUndefined(); + + const context = {} as AutomationContext; + const out: any = await engine.execute('parent', context); + expect(out.success).toBe(true); + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'call'); + expect(step.status).toBe('success'); + expect(step.childRunIds, 'the call started no run').toBeUndefined(); + }); +}); + +/** + * A stand-in for the `sys_automation_run` table, enough for + * {@link ObjectStoreSuspendedRunStore}'s terminal write and read: rows keyed + * by id, `where` by equality. No `delete`, so the write-time retention prune + * is off and every row stays. + */ +function rowTable(): SuspendedRunStoreEngine & { rows: Map } { + const rows = new Map(); + // Equality only: an operator or a combinator is refused, never read as a + // field name. + const matches = (row: any, where: Record | undefined) => + !where || Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`rowTable: unsupported combinator ${k}`); + if (v !== null && typeof v === 'object') throw new Error(`rowTable: unsupported operator on ${k}`); + return row[k] === v; + }); + return { + rows, + async find(_object, options) { + const where = options?.where as Record | undefined; + if (where && Object.keys(where).length === 1 && typeof where.id === 'string') { + const row = rows.get(where.id); + return row ? [row] : []; + } + const out = [...rows.values()].filter((r) => matches(r, where)); + return typeof options?.limit === 'number' ? out.slice(0, options.limit) : out; + }, + async insert(_object, data) { + rows.set(String(data.id), { ...data }); + return data; + }, + async update(_object, data, options) { + // As strict as `ObjectQL.update`: the store updates its row by id. + const dispatch = assertEngineUpdateDispatch(data, options); + if (dispatch.kind !== 'by-id') throw new Error('rowTable: an update by id only'); + const id = String(dispatch.id); + rows.set(id, { ...(rows.get(id) ?? { id }), ...data }); + return rows.get(id); + }, + }; +} + +const flushWrites = () => new Promise((r) => setTimeout(r, 20)); +const runIdLike = (n: number) => `run_${String(n).padStart(8, '0')}-0000-4000-8000-000000000000`; + +describe('[ADR-0162 item 8] the links a step carries are bounded (seat ruling 7258590209)', () => { + it(`a map that starts more item runs than a step names: the first ${MAX_STEP_CHILD_RUN_IDS}, and the step says the list is cut`, async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + const items = Array.from({ length: MAX_STEP_CHILD_RUN_IDS + 5 }, (_, i) => ({ id: `rec_${i}` })); + engine.registerFlow('batch', chain('batch', [{ ...map('item', items), config: { flowName: 'item', collection: items, itemObject: 'thing' } }]) as any); + const context = {} as AutomationContext; + expect(((await engine.execute('batch', context)) as any).success).toBe(true); + + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + expect(step.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(new Set(step.childRunIds).size).toBe(MAX_STEP_CHILD_RUN_IDS); + expect(step.childRunIdsTruncated).toBe(true); + // The first ones started, in order: the ids name the runs of the first + // items, the first id the first item's run, the last the 200th's. + const first: any = await engine.getRun(step.childRunIds[0]); + const last: any = await engine.getRun(step.childRunIds[MAX_STEP_CHILD_RUN_IDS - 1]); + expect(first?.flowName).toBe('item'); + expect(first?.trigger?.recordId).toBe('rec_0'); + expect(last?.trigger?.recordId).toBe(`rec_${MAX_STEP_CHILD_RUN_IDS - 1}`); + }); + + it(`a map of exactly ${MAX_STEP_CHILD_RUN_IDS} items names them all and is not marked`, async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + const items = Array.from({ length: MAX_STEP_CHILD_RUN_IDS }, (_, i) => i); + engine.registerFlow('batch', chain('batch', [map('item', items)]) as any); + const context = {} as AutomationContext; + await engine.execute('batch', context); + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + expect(step.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(step.childRunIdsTruncated, 'a whole list carries no mark').toBeUndefined(); + }); + + it('a map of 1,600 items, stored and read back after a restart: the history row keeps every step the run logged', async () => { + // [M5 of review record 7258563513] 1,600 run ids named whole are more + // than the row's 64 KB alone: halving the log from its head reached + // the `map` step, the last one logged, and the row stored no step at + // all. Bounded, the row keeps the three steps it kept before steps + // named their child runs (an `end` node logs no step). + const table = rowTable(); + const engine = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); + engine.registerFlow('item', chain('item', [NOOP]) as any); + engine.registerFlow('batch', chain('batch', [{ ...NOOP, id: 'prepare' }, map('item', Array.from({ length: 1600 }, (_, i) => i))]) as any); + const context = {} as AutomationContext; + expect(((await engine.execute('batch', context)) as any).success).toBe(true); + const runId = engine.runStartedFor(context)!; + await flushWrites(); + + const restarted = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); + const stored: any = await restarted.getRun(runId); + expect(stored?.status).toBe('completed'); + expect(stored.steps.map((s: any) => s.nodeId)).toEqual(['start', 'prepare', 'each']); + const each = stored.steps[2]; + expect(each.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(each.childRunIdsTruncated).toBe(true); + expect(table.rows.get(`run_${runId}`).steps_json.length).toBeLessThanOrEqual(64 * 1024); + }); +}); + +describe('[ADR-0162 item 8] the history row sheds the links before it drops a step (seat ruling 7258590209)', () => { + const delegating = (n: number): StepLogEntry => ({ + nodeId: `each_${n}`, nodeType: 'map', status: 'success', startedAt: '2026-01-01T00:00:01.000Z', + childRunIds: Array.from({ length: MAX_STEP_CHILD_RUN_IDS }, (_, i) => runIdLike(n * 1000 + i)), + childRunIdsTruncated: true, + }); + const plain = (nodeId: string): StepLogEntry => ({ nodeId, nodeType: 'assignment', status: 'success', startedAt: '2026-01-01T00:00:01.000Z' }); + const record = (steps: StepLogEntry[]): RunRecord => ({ + runId: 'r1', flowName: 'sweep', status: 'completed', startedAt: '2026-01-01T00:00:00.000Z', durationMs: 5, steps, + }); + + it('a log its links carry over the cap: every step is kept, each step that named child runs marked and without them', async () => { + const table = rowTable(); + const store = new ObjectStoreSuspendedRunStore(table, createTestLogger()); + const steps = [plain('start'), ...Array.from({ length: 8 }, (_, n) => delegating(n)), plain('end')]; + expect(JSON.stringify(steps).length, 'the fixture is over the row cap with its links').toBeGreaterThan(64 * 1024); + await store.recordTerminal(record(steps)); + + const kept = (await store.loadTerminal('r1'))!.steps!; + expect(kept.map((s) => s.nodeId), 'the steps a log without links keeps').toEqual(steps.map((s) => s.nodeId)); + for (const s of kept.slice(1, -1)) { + expect(s.childRunIds).toBeUndefined(); + expect(s.childRunIdsTruncated).toBe(true); + } + expect(kept[0].childRunIdsTruncated, 'a step that named no child run is not marked').toBeUndefined(); + expect(kept[kept.length - 1]).toEqual(plain('end')); + }); + + it('a log under the cap keeps its links as they were', async () => { + const table = rowTable(); + const store = new ObjectStoreSuspendedRunStore(table, createTestLogger()); + const steps = [plain('start'), delegating(0), plain('end')]; + await store.recordTerminal(record(steps)); + expect((await store.loadTerminal('r1'))!.steps).toEqual(steps); + }); +}); diff --git a/packages/services/service-automation/src/suspended-run-store.ts b/packages/services/service-automation/src/suspended-run-store.ts index d1743db3cc7..d925cc5eb86 100644 --- a/packages/services/service-automation/src/suspended-run-store.ts +++ b/packages/services/service-automation/src/suspended-run-store.ts @@ -1241,9 +1241,22 @@ function readConsumedSuspensionDropNotice(row: any): ConsumedSuspensionDropNotic * BYTES — a few huge step errors can still blow up a row. When over, the step * tail is halved until it fits (the newest steps carry the failure); an empty * result stores `null`. + * + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] Before any + * step goes, the links to child runs do ({@link shedChildRunIds}): a log + * over the cap is stored without every step's `childRunIds`, each step that + * named child runs marked `childRunIdsTruncated: true`, and only a log still + * over the cap without them is halved. The links are what the log gained + * when steps began to name their child runs, so shedding them first keeps + * the steps a log without them kept; the mark is what keeps a reader from + * taking a step that names no run for one that started none. A mark costs + * 28 bytes on each step it lands on, so a log that fits the cap without its + * links by less than its marks' bytes is halved, where a log that never + * named a child run was not. */ function serializeStepsBounded(steps: RunRecord['steps']): string | null { let tail = steps ?? []; + if (tail.length > 0 && JSON.stringify(tail).length > MAX_STEPS_JSON_BYTES) tail = tail.map(shedChildRunIds); while (tail.length > 0) { const json = JSON.stringify(tail); if (json.length <= MAX_STEPS_JSON_BYTES) return json; @@ -1252,6 +1265,18 @@ function serializeStepsBounded(steps: RunRecord['steps']): string | null { return null; } +/** + * [ADR-0162 Execution item 8] One step without its links to child runs, for + * {@link serializeStepsBounded}: a step that named any carries + * `childRunIdsTruncated: true` in their place; any other step is returned as + * it was. + */ +function shedChildRunIds(step: NonNullable[number]): NonNullable[number] { + if (!Array.isArray(step?.childRunIds) && step?.childRunIdsTruncated !== true) return step; + const { childRunIds: _shed, ...rest } = step; + return { ...rest, childRunIdsTruncated: true }; +} + /** * JSON-encode a run summary under {@link MAX_SUMMARY_JSON_BYTES} (#4354). * diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index 01e45087c3e..dd1084bc933 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -55,6 +55,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'approval.comment', 'approval.escalated', + 'approval.flow_not_continued', 'approval.ooo_skipped', 'approval.ooo_substituted', 'approval.reassigned', @@ -63,6 +64,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'approval.requested', 'approval.returned', 'approval.sla_breached', + 'approval.status_mirror_refused', 'auth.phone_invite', 'auth.phone_otp', 'collab.mention', diff --git a/packages/services/service-storage/src/upload-link-copy.test.ts b/packages/services/service-storage/src/upload-link-copy.test.ts index 685e23314c3..ba2c0d1af78 100644 --- a/packages/services/service-storage/src/upload-link-copy.test.ts +++ b/packages/services/service-storage/src/upload-link-copy.test.ts @@ -127,6 +127,26 @@ describe('#32712 — the upload-link page\'s sentences', () => { .toBe('上传被拒绝:Amount must be positive.'); }); + /** + * [ADR-0162 D8] The page carries a closed-state sentence beside the approval + * one, in every language it carries. A closed-state refusal reaches the page + * with the engine's declared sentence, which the page shows; the code-only + * lookup below answers a `RECORD_LOCKED` that declares none. Choosing + * `recordClosed` by the lock read's reason stays with Execution item 2: this + * pins the table, not a selection. + */ + it('carries a closed-state sentence in every language, not the approval one; a RECORD_LOCKED with no declared sentence reads the approval one', () => { + for (const tag of PLATFORM_LOCALE_TAGS) { + const copy = UPLOAD_LINK_COPY[copyLocaleOf(tag)!]; + expect(copy.recordClosed.trim(), tag).not.toBe(''); + expect(copy.recordClosed, tag).not.toBe(copy.recordLocked); + expect(uploadLinkRefusalText(copy, 409, 'RECORD_LOCKED', 'producer text'), tag).toBe(copy.recordLocked); + } + expect(Object.keys(UPLOAD_LINK_COPY).sort()).toEqual( + [...new Set(PLATFORM_LOCALE_TAGS.map((tag) => copyLocaleOf(tag)!))].sort(), + ); + }); + it('writes the expiry in the page\'s language, in UTC and saying so', () => { const at = '2026-11-12T21:54:00.000Z'; expect(formatUploadLinkExpiry(UPLOAD_LINK_COPY['zh-CN'], at)).toBe('2026年11月12日 UTC 21:54'); diff --git a/packages/services/service-storage/src/upload-link-copy.ts b/packages/services/service-storage/src/upload-link-copy.ts index 06f2394b79a..617a70d82e5 100644 --- a/packages/services/service-storage/src/upload-link-copy.ts +++ b/packages/services/service-storage/src/upload-link-copy.ts @@ -47,8 +47,21 @@ export interface UploadLinkRefusalCopy { notAllowed: string; /** `FIELD_NOT_ACCESSIBLE`: the field is read-only on the record (statically or in its current state). */ fieldReadOnly: string; - /** `RECORD_LOCKED`: a pending approval locks the record. */ + /** + * `RECORD_LOCKED` that carries no declared sentence of its own. A refusal + * that declares one (`userMessage`) is shown with that sentence instead + * (`storage-routes.ts` `relayUploadLinkRefusal`). + */ recordLocked: string; + /** + * [ADR-0162 D8] The page's sentence for a record in one of its object's + * closed states. A closed-state refusal reaches this page with the engine's + * declared catalog sentence (`record_closed*`, worded in the link user's + * resolved context, `record-file-access.ts` `consumeUploadLinkFiles`) as + * its `userMessage`, and the page shows that sentence. Choosing this + * entry by the lock read's reason stays with ADR-0162 Execution item 2. + */ + recordClosed: string; /** `RECORD_NOT_FOUND`: the record is gone, or out of the user's reach. */ recordGone: string; /** Any `503`: the platform could not take the upload now. */ @@ -156,6 +169,7 @@ export const UPLOAD_LINK_COPY: Record = { fieldReadOnly: 'Nothing was attached: the field this link was made for is read-only on this record, so it cannot take a file.', recordLocked: 'Nothing was attached: the record is locked while an approval is in progress. Ask for a new link once the approval is decided.', + recordClosed: 'Nothing was attached: the record is closed, so no file can be added to it.', recordGone: 'Nothing was attached: the record this link was made for no longer exists, or you can no longer reach it.', unavailable: 'The upload cannot be taken right now. Try again in a few minutes.', refused: (reason) => reason, @@ -200,6 +214,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未添加任何文件:你已无法再向这条记录添加文件。', fieldReadOnly: '未添加任何文件:此链接对应的字段在这条记录上是只读的,无法接收文件。', recordLocked: '未添加任何文件:这条记录正在审批中,已被锁定。请在审批完成后索取新的链接。', + recordClosed: '未添加任何文件:这条记录已关闭,无法再添加文件。', recordGone: '未添加任何文件:此链接对应的记录已不存在,或你已无法访问它。', unavailable: '暂时无法接收上传。请几分钟后重试。', refused: (reason) => `上传被拒绝:${reason}`, @@ -244,6 +259,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '未新增任何檔案:你已無法再向這筆記錄新增檔案。', fieldReadOnly: '未新增任何檔案:此連結對應的欄位在這筆記錄上是唯讀的,無法接收檔案。', recordLocked: '未新增任何檔案:這筆記錄正在簽核中,已被鎖定。請在簽核完成後索取新的連結。', + recordClosed: '未新增任何檔案:這筆記錄已關閉,無法再新增檔案。', recordGone: '未新增任何檔案:此連結對應的記錄已不存在,或你已無法存取它。', unavailable: '暫時無法接收上傳。請幾分鐘後重試。', refused: (reason) => `上傳遭拒:${reason}`, @@ -291,6 +307,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '何も追加されませんでした: このレコードにはもうファイルを追加できません。', fieldReadOnly: '何も追加されませんでした: このリンクの項目はこのレコードでは読み取り専用のため、ファイルを受け付けません。', recordLocked: '何も追加されませんでした: 承認の処理中のため、レコードはロックされています。承認が完了してから新しいリンクを依頼してください。', + recordClosed: '何も追加されませんでした: レコードはクローズ済みのため、ファイルを追加できません。', recordGone: '何も追加されませんでした: このリンクのレコードは存在しないか、アクセスできなくなっています。', unavailable: '現在アップロードを受け付けられません。数分後にもう一度お試しください。', refused: (reason) => `アップロードが拒否されました: ${reason}`, @@ -338,6 +355,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: '아무것도 추가되지 않았습니다: 이 레코드에 더 이상 파일을 추가할 수 없습니다.', fieldReadOnly: '아무것도 추가되지 않았습니다: 이 링크의 필드는 이 레코드에서 읽기 전용이므로 파일을 받을 수 없습니다.', recordLocked: '아무것도 추가되지 않았습니다: 승인이 진행 중이어서 레코드가 잠겨 있습니다. 승인이 결정된 후 새 링크를 요청하세요.', + recordClosed: '아무것도 추가되지 않았습니다: 레코드가 종료되어 파일을 추가할 수 없습니다.', recordGone: '아무것도 추가되지 않았습니다: 이 링크의 레코드가 더 이상 없거나 더 이상 접근할 수 없습니다.', unavailable: '지금은 업로드를 받을 수 없습니다. 몇 분 후에 다시 시도하세요.', refused: (reason) => `업로드가 거부되었습니다: ${reason}`, @@ -384,6 +402,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'No se ha adjuntado nada: ya no puedes añadir archivos a este registro.', fieldReadOnly: 'No se ha adjuntado nada: el campo de este enlace es de solo lectura en este registro, así que no admite archivos.', recordLocked: 'No se ha adjuntado nada: el registro está bloqueado mientras hay una aprobación en curso. Pide un enlace nuevo cuando se haya resuelto la aprobación.', + recordClosed: 'No se ha adjuntado nada: el registro está cerrado, así que no se le puede añadir ningún archivo.', recordGone: 'No se ha adjuntado nada: el registro de este enlace ya no existe o ya no tienes acceso a él.', unavailable: 'Ahora mismo no se puede recibir la subida. Vuelve a intentarlo dentro de unos minutos.', refused: (reason) => `Se ha rechazado la subida: ${reason}`, @@ -428,6 +447,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'لم يُرفق شيء: لم يعد بإمكانك إضافة ملفات إلى هذا السجل.', fieldReadOnly: 'لم يُرفق شيء: حقل هذا الرابط للقراءة فقط في هذا السجل، لذا لا يمكنه استقبال ملف.', recordLocked: 'لم يُرفق شيء: السجل مقفل أثناء وجود موافقة قيد الإجراء. اطلب رابطًا جديدًا بعد البت في الموافقة.', + recordClosed: 'لم يُرفق شيء: السجل مغلق، لذا لا يمكن إضافة ملف إليه.', recordGone: 'لم يُرفق شيء: سجل هذا الرابط لم يعد موجودًا، أو لم يعد بإمكانك الوصول إليه.', unavailable: 'لا يمكن استقبال الرفع الآن. حاول مرة أخرى بعد بضع دقائق.', refused: (reason) => `رُفض الرفع: ${reason}`, @@ -475,6 +495,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Rien n’a été joint : vous ne pouvez plus ajouter de fichier à cet enregistrement.', fieldReadOnly: 'Rien n’a été joint : le champ de ce lien est en lecture seule sur cet enregistrement, il ne peut donc pas recevoir de fichier.', recordLocked: 'Rien n’a été joint : l’enregistrement est verrouillé pendant qu’une approbation est en cours. Demandez un nouveau lien une fois l’approbation décidée.', + recordClosed: 'Rien n’a été joint : l’enregistrement est clôturé, on ne peut plus y ajouter de fichier.', recordGone: 'Rien n’a été joint : l’enregistrement de ce lien n’existe plus, ou vous n’y avez plus accès.', unavailable: 'L’envoi ne peut pas être reçu pour le moment. Réessayez dans quelques minutes.', refused: (reason) => `L’envoi a été refusé : ${reason}`, @@ -521,6 +542,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Nada foi anexado: você não pode mais adicionar arquivos a este registro.', fieldReadOnly: 'Nada foi anexado: o campo deste link é somente leitura neste registro, então não pode receber um arquivo.', recordLocked: 'Nada foi anexado: o registro está bloqueado enquanto uma aprovação está em andamento. Peça um novo link quando a aprovação for decidida.', + recordClosed: 'Nada foi anexado: o registro está encerrado, então não é possível adicionar arquivos a ele.', recordGone: 'Nada foi anexado: o registro deste link não existe mais, ou você não tem mais acesso a ele.', unavailable: 'O envio não pode ser recebido agora. Tente novamente em alguns minutos.', refused: (reason) => `O envio foi recusado: ${reason}`, @@ -568,6 +590,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Ничего не прикреплено: вы больше не можете добавлять файлы к этой записи.', fieldReadOnly: 'Ничего не прикреплено: поле этой ссылки в этой записи доступно только для чтения и не может принять файл.', recordLocked: 'Ничего не прикреплено: запись заблокирована, пока идёт согласование. Попросите новую ссылку, когда по согласованию будет принято решение.', + recordClosed: 'Ничего не прикреплено: запись закрыта, поэтому к ней нельзя добавить файл.', recordGone: 'Ничего не прикреплено: записи этой ссылки больше нет, или у вас больше нет к ней доступа.', unavailable: 'Сейчас загрузку принять невозможно. Попробуйте ещё раз через несколько минут.', refused: (reason) => `Загрузка отклонена: ${reason}`, @@ -615,6 +638,7 @@ export const UPLOAD_LINK_COPY: Record = { notAllowed: 'Es wurde nichts angehängt: Sie können diesem Datensatz keine Datei mehr hinzufügen.', fieldReadOnly: 'Es wurde nichts angehängt: Das Feld dieses Links ist in diesem Datensatz schreibgeschützt und kann keine Datei aufnehmen.', recordLocked: 'Es wurde nichts angehängt: Der Datensatz ist gesperrt, solange eine Genehmigung läuft. Fordern Sie einen neuen Link an, sobald über die Genehmigung entschieden ist.', + recordClosed: 'Es wurde nichts angehängt: Der Datensatz ist abgeschlossen, daher kann keine Datei hinzugefügt werden.', recordGone: 'Es wurde nichts angehängt: Der Datensatz dieses Links existiert nicht mehr, oder Sie haben keinen Zugriff mehr darauf.', unavailable: 'Der Upload kann gerade nicht angenommen werden. Versuchen Sie es in einigen Minuten erneut.', refused: (reason) => `Der Upload wurde abgelehnt: ${reason}`, diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index 6f2879d733f..0fc1f645e2b 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -161,6 +161,8 @@ "automation/ExecutionLog:variables", "automation/ExecutionLog:waitMs", "automation/ExecutionStepLog:branch", + "automation/ExecutionStepLog:childRunIds", + "automation/ExecutionStepLog:childRunIdsTruncated", "automation/ExecutionStepLog:completedAt", "automation/ExecutionStepLog:droppedFields", "automation/ExecutionStepLog:durationMs", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 4b272e5eca0..10404df0f62 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -684,6 +684,7 @@ "data/Object:actions", "data/Object:activityMilestones", "data/Object:attachedOnRead", + "data/Object:closedStates", "data/Object:color", "data/Object:datasource", "data/Object:defaultRowScope", diff --git a/packages/spec/authorable-surface/kernel.json b/packages/spec/authorable-surface/kernel.json index 6e7a3a8f0f6..de279dff3df 100644 --- a/packages/spec/authorable-surface/kernel.json +++ b/packages/spec/authorable-surface/kernel.json @@ -175,6 +175,7 @@ "kernel/ExecutionContext:authGate", "kernel/ExecutionContext:currency", "kernel/ExecutionContext:email", + "kernel/ExecutionContext:flowRootRunId", "kernel/ExecutionContext:flowRunId", "kernel/ExecutionContext:impersonatedBy", "kernel/ExecutionContext:isSystem", diff --git a/packages/spec/docs/references/api/metadata.md b/packages/spec/docs/references/api/metadata.md index eb6af874aaf..abab9a8a1fb 100644 --- a/packages/spec/docs/references/api/metadata.md +++ b/packages/spec/docs/references/api/metadata.md @@ -957,6 +957,7 @@ Metadata query with filtering, sorting, and pagination | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/docs/references/kernel/execution-context.md b/packages/spec/docs/references/kernel/execution-context.md index 90ba68375bf..10b7f761dfa 100644 --- a/packages/spec/docs/references/kernel/execution-context.md +++ b/packages/spec/docs/references/kernel/execution-context.md @@ -70,6 +70,7 @@ const result = AuthGateCodeSchema.parse(data); | **rlsMembership** | `Record` | optional | | | **isSystem** | `boolean` | optional (default: `false`) | | | **flowRunId** | `string` | optional | | +| **flowRootRunId** | `string` | optional | | | **skipTriggers** | `boolean` | optional | | | **skipAutomations** | `boolean` | optional | | | **seedReplay** | `boolean` | optional | | diff --git a/packages/spec/docs/references/system/migration.md b/packages/spec/docs/references/system/migration.md index dd5dd494e6c..6b253c0cf78 100644 --- a/packages/spec/docs/references/system/migration.md +++ b/packages/spec/docs/references/system/migration.md @@ -356,6 +356,7 @@ Create a new object | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/docs/references/system/migration.part-2.md b/packages/spec/docs/references/system/migration.part-2.md index 8ab56a69140..1cb7541d1d3 100644 --- a/packages/spec/docs/references/system/migration.part-2.md +++ b/packages/spec/docs/references/system/migration.part-2.md @@ -200,6 +200,7 @@ Create a new object | **validations** | `any[]` | optional | Object-level validation rules | | **activityMilestones** | `{ field: string; value: string; summary: string; type?: string }[]` | optional | Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2). | | **uiReadonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key. | +| **closedStates** | `Record` | optional | States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to the list of that field's option values that close the record, e.g. `{ status: ['paid', 'void'], approval_status: ['approved'] }`. A record is closed when ANY listed field holds one of its listed values, read off the stored row. While closed, the record and its direct master_detail lines are closed to change for every caller that is not a system context: the record is not updated or deleted, and no line is created, updated, deleted or moved. The field must declare inline options; each listed value is one of them; a list is not empty and repeats nothing. A field or option a declaration names cannot be removed or retyped while it names it. A line object declares nothing to be closed with its master, and may declare its own. Independent of any state_machine rule on the field. | | **nameField** | `string` | optional | [ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). | | **displayNameField** | `string` | optional | [DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField. | | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 14429b382e9..495f4e80c70 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -341,6 +341,12 @@ "evidence": "ui/packages/core/src/evaluator/handLock.ts#effectiveUiReadonlyWhen (a field's own `uiReadonly: true` / `uiReadonlyWhen` wins, else the object's predicate; `uiReadonly: false` reads as absent) read by #fieldReadOnlyByHand, #fieldHasConditionalHandLock and #fieldLockPredicates, which every hand surface reads with the object definition beside the field: the record page (ui/packages/plugin-detail/src/DetailSection.tsx, HeaderHighlight.tsx, InlineEditSaveBar.tsx, renderers/recordPathStageChange.tsx), the grid cell (ui/packages/plugin-grid/src/objectGridCellFacts.ts#cellReadOnlyKind) and its operand fetch (objectGridRowLoad.ts, ui/packages/plugin-list/src/ListView.tsx), kanban and calendar drops, the Gantt (ui/packages/plugin-gantt/src/ganttHandLock.ts), the timesheet cell, and the edit dialog's form fields (ui/packages/plugin-form/src/sectionFields.ts#fromObjectSchema, ObjectForm.tsx, ui/packages/app-shell/src/utils/editFormLockedByState.ts); packages/runtime/src/domains/mcp.ts#describeServedObject and packages/mcp/src/mcp-server-runtime.ts#describeServedObject (describe_object); packages/lint/src/validate-expressions.ts (objectstack validate)", "note": "renderer only, by ruling (the two-tier field-lock model, its object level): while TRUE no person edits any field of an existing record at the console surfaces a field's own `uiReadonlyWhen` locks; a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead (`uiReadonly: false` is not a declaration: the field follows the object lock; the opt-out spelling is a field `uiReadonlyWhen` of P`false`). The engine never reads it, so REST, import, action and flow writes keep every field, judged by validations. Fail-closed on a fault, as the field key. The console has no person-triggered record duplicate, so no clone surface reads it; the REST clone door is an API write and keeps every value." }, + "closedStates": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidence": "packages/objectql/src/closed-state-lock.ts#closedStateUnitOf (the engine's read of the key: the record's own closed values, and each master whose closed values bind a line); packages/objectql/src/closed-state-lock.ts#judgeClosedStateByIdWrite (the by-id update and delete door); packages/objectql/src/closed-state-lock.ts#judgeClosedStatePredicateWrite (the many-row door: one existence probe, or the matched-row read under the per-row ceiling); packages/objectql/src/registry-closed-state-fold.ts#withPackagedClosedStates (the fold keeps a package's list against a tenant overlay); packages/qa/dogfood/test/closed-state-lock.test.ts (runtime proof on SQLite, with and without the line probe and transactions); packages/spec/src/data/closed-states.ts#refuseDishonestClosedStates (the authoring refusals at parse and at the save door)", + "note": "LIVE (ADR-0162 D2-D7, D10; card #37768 slice B): a record whose stored state is a listed value is closed, and so are its direct master_detail lines; every write a system context does not make is refused 409 RECORD_LOCKED, a many-row write whole and before any row is written; a cascade that reaches a closed record removes no row; a restore under a live closed master is refused; a referential clear and the recycle-bin relink land. The lock runs after the middleware gates and before the before-hooks. The extension and overlay fold cannot shorten a package's list or break a field it names. The refusal's sentences (D8) are slice C of the same trunk branch, which does not merge before C lands." + }, "validations": { "status": "live", "verifiedAt": "2026-08-28", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index 9b5400d17eb..b5ca968ce9f 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 100 | 0 | 0 | 1 | 1 | 102 | +| `object` | 101 | 0 | 0 | 1 | 1 | 103 | diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 66ff4deb1ab..8aedf2dab8d 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -961,6 +961,16 @@ export const ERROR_CODE_LEDGER = { // assembled vocabulary rejects, both 422/INVALID_METADATA. Provenance, not // identity, per this file's header. 'INVALID_METADATA', + // [ADR-0162 D4, D8] 409 from the closed-state lock (`closed-state-lock.ts`): + // a write a system context does not make reaches a record whose stored + // state its object lists in `closedStates`, or a line of one, a cascade + // that reaches one, or a restore under one; a many-row write is refused + // whole before any row is written. `reason` tells the four apart, and + // `lockReason: 'closed_state'` tells it from the approval lock. Third + // EMITTER of the code `@objectstack/plugin-approvals` registers for the + // pending-approval lock and `@objectstack/rest` relays: one condition, + // the record is not open to change, one code. Provenance, not identity. + 'RECORD_LOCKED', 'ERR_READONLY_FIELD_REJECTED', // strictReadonlyWrites: the write would strip caller-supplied fields, so it was refused (#5126; since #6437 that covers the primary_key strip too — one code, `drops` carries the per-reason breakdown) 'ERR_SUMMARY_RECOMPUTE', // [#8844] A system-context insert on a tenant-scoped application object diff --git a/packages/spec/src/automation/execution.zod.ts b/packages/spec/src/automation/execution.zod.ts index 2184cfca6af..fa1aae8b0ed 100644 --- a/packages/spec/src/automation/execution.zod.ts +++ b/packages/spec/src/automation/execution.zod.ts @@ -216,6 +216,17 @@ export const ExecutionStepLogSchema = lazySchema(() => z.object({ .describe('Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none'), droppedFields: z.array(DroppedFieldsEventSchema).optional() .describe('The data engine\'s own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing'), + // [ADR-0162 Execution item 8] The child runs a delegating step started, so a + // reader of one run can reach every run of its tree from the step log alone: + // a child's own log is a row of its own, and nothing else on the parent's + // log names it once the parent has moved past the step. + childRunIds: z.array(z.string()).optional() + .describe('Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed'), + // [ADR-0162 Execution item 8] Seat ruling 7258590209 on #37767: the list is + // bounded, and a step whose list is not whole says so, so a reader never + // takes a cut list, or a missing one, for every child run the step started. + childRunIdsTruncated: z.literal(true).optional() + .describe('Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run\'s history row shed the step\'s links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started'), })); export type ExecutionStepLog = z.input; diff --git a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts index 7959ab3ef03..b9ddeeeff1b 100644 --- a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts +++ b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts @@ -253,6 +253,8 @@ describe('MAIN — the preprocess-wrapped collection key is IN the refusal set', 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'fieldTabs', @@ -300,18 +302,24 @@ describe("TODAY-INVARIANCE — the fix moves no key on today's ObjectSchema", () const setUnder = (shape: Record, walk: Walk) => Object.keys(shape).filter((key) => key !== 'fields' && walk(shape[key])); - it('all three candidate readings derive the SAME refusal set', async () => { + // [ADR-0162 D1] `closedStates` is the first collection key on the real shape + // whose record sits behind a preprocess stage (the `__proto__` guard): it is + // exactly the key this rule exists for. The landed reading and `in || out` + // carry it; the in-only reading misses it, and misses nothing else. + it('the landed rule and `in || out` derive the same refusal set; the in-only reading misses only the preprocess-wrapped `closedStates`', async () => { const shape = await realShape(); - const inOnly = setUnder(shape, inOnlyWalk); - expect(setUnder(shape, authorableWalk), 'the landed rule moved a key on the real shape').toEqual(inOnly); - expect(setUnder(shape, eitherSideWalk), '`in || out` would move a key on the real shape').toEqual(inOnly); - expect(inOnly).toEqual([ + const landed = setUnder(shape, authorableWalk); + expect(setUnder(shape, eitherSideWalk), '`in || out` would move a key on the real shape').toEqual(landed); + expect(setUnder(shape, inOnlyWalk)).toEqual(landed.filter((key) => key !== 'closedStates')); + expect(landed).toEqual([ 'attachedOnRead', 'indexes', 'fieldGroups', 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'fieldTabs', diff --git a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts index e30a4df1642..9a0e4a59e23 100644 --- a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts @@ -66,6 +66,8 @@ const COLLECTION_KEYS_IN_SHAPE_ORDER = [ 'requiredPermissions', 'validations', 'activityMilestones', + // [ADR-0162 D1] `closedStates` — the object's closed states, a map keyed by its fields. + 'closedStates', 'highlightFields', 'relatedLists', 'fieldTabs', @@ -148,6 +150,8 @@ describe("composeStacks objectConflict: 'merge' — a collection both objects de ['requiredPermissions', ['crm.read'], ['billing.read']], ['attachedOnRead', { viewer: { can_act: 'boolean' } }, { viewer: { can_act: 'boolean', is_submitter: 'boolean' } }], ['membershipKeys', { mine_ids: { userField: 'owner', valueField: 'title' } }, { mine_ids: { userField: 'owner', valueField: 'body' } }], + // [ADR-0162 D1] Two packages that close one object on different states: neither may silently win. + ['closedStates', { status: ['paid'] }, { status: ['paid', 'void'] }], ] as const)("refuses two objects declaring different '%s'", (key, left, right) => { const a = defineStack({ manifest: mf('com.example.a'), objects: [obj('shared', { [key]: left })] }, { strict: false }); const b = defineStack({ manifest: mf('com.example.b'), objects: [obj('shared', { [key]: right })] }, { strict: false }); diff --git a/packages/spec/src/data/closed-states.test.ts b/packages/spec/src/data/closed-states.test.ts new file mode 100644 index 00000000000..b72ff7d2f5c --- /dev/null +++ b/packages/spec/src/data/closed-states.test.ts @@ -0,0 +1,234 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { ObjectSchema } from './object.zod'; +import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; +import { ObjectStackDefinitionSchema } from '../stack.zod'; + +// --------------------------------------------------------------------------- +// [ADR-0162 D1] `closedStates` — the key and its authoring refusals. +// +// The key maps a stored, single-value `select` field of the object to a +// non-empty list of that field's own option values, each listed once. Every +// declaration that breaks one of those rules is ONE located `custom` issue at +// parse, at the save door (the `object` metadata schema) and at the stack +// door; so is the declaration a removed or retyped field, or a removed option, +// leaves behind. The pins bear weight both ways: the ADR's own two-field +// example parses clean and keeps its value. +// --------------------------------------------------------------------------- + +const STATUS_OPTIONS = [ + { label: 'Draft', value: 'draft' }, + { label: 'Paid', value: 'paid' }, + { label: 'Void', value: 'void' }, +]; +const APPROVAL_OPTIONS = [ + { label: 'Pending', value: 'pending' }, + { label: 'Approved', value: 'approved' }, + { label: 'Rejected', value: 'rejected' }, +]; + +const invoice = (closedStates: unknown, fields: Record = {}) => ({ + name: 'invoice', + fields: { + name: { type: 'text', label: 'Number' }, + status: { type: 'select', label: 'Status', options: STATUS_OPTIONS }, + approval_status: { type: 'select', label: 'Approval', options: APPROVAL_OPTIONS }, + ...fields, + }, + ...(closedStates === undefined ? {} : { closedStates }), +}); + +const ADR_EXAMPLE = { status: ['paid', 'void'], approval_status: ['approved'] }; + +/** The one issue a refused declaration carries: its code and path, and the message. */ +function refusedAt(input: unknown, path: (string | number)[]): string { + const parsed = ObjectSchema.safeParse(input); + expect(parsed.success, 'the declaration must NOT parse clean').toBe(false); + if (parsed.success) throw new Error('unreachable'); + expect(parsed.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', path]]); + return parsed.error.issues[0]!.message; +} + +describe('[ADR-0162 D1] `closedStates` — accepted shapes', () => { + it('accepts the ADR example: two fields, each with its own closing values, and keeps it as written', () => { + const parsed = ObjectSchema.safeParse(invoice(ADR_EXAMPLE)); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + if (!parsed.success) return; + expect(parsed.data.closedStates).toEqual(ADR_EXAMPLE); + }); + + it('is optional: an object without the key parses, and no parsed object grows one (control)', () => { + const parsed = ObjectSchema.safeParse(invoice(undefined)); + expect(parsed.success).toBe(true); + if (!parsed.success) return; + expect('closedStates' in parsed.data).toBe(false); + }); + + it('needs no `state_machine` rule on the field, and a `state_machine` rule does not need the key', () => { + expect(ObjectSchema.safeParse(invoice({ status: ['paid'] })).success).toBe(true); + const machine = { + ...invoice(undefined), + validations: [{ + type: 'state_machine', + name: 'status_flow', + message: 'Illegal status move', + field: 'status', + transitions: { draft: ['paid', 'void'], paid: [], void: [] }, + }], + }; + const parsed = ObjectSchema.safeParse(machine); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + if (!parsed.success) return; + expect('closedStates' in parsed.data).toBe(false); + }); + + it('`create()` keeps the declaration', () => { + const created = ObjectSchema.create(invoice(ADR_EXAMPLE) as never) as { closedStates?: unknown }; + expect(created.closedStates).toEqual(ADR_EXAMPLE); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — refused where the object is authored', () => { + it('refuses a key that names no field of the object', () => { + const message = refusedAt(invoice({ state: ['paid'] }), ['closedStates', 'state']); + expect(message).toContain('declares no field `state`'); + }); + + it('refuses a field that is not a `select`', () => { + const message = refusedAt(invoice({ name: ['x'] }), ['closedStates', 'name']); + expect(message).toContain('is a `text` field, not a single-value `select`'); + }); + + it('refuses a `multiple: true` select', () => { + const tags = { type: 'select', label: 'Tags', multiple: true, options: STATUS_OPTIONS }; + const message = refusedAt(invoice({ tags: ['paid'] }, { tags }), ['closedStates', 'tags']); + expect(message).toContain('a `multiple: true` `select`'); + }); + + it('refuses a `radio`, an option type that is not a `select` (the key names a select)', () => { + const stage = { type: 'radio', label: 'Stage', options: STATUS_OPTIONS }; + refusedAt(invoice({ stage: ['paid'] }, { stage }), ['closedStates', 'stage']); + }); + + it('refuses a `picklist`-backed select: its options are not declared on this object', () => { + const kind = { type: 'select', label: 'Kind', picklist: 'invoice_kind' }; + const message = refusedAt(invoice({ kind: ['credit'] }, { kind }), ['closedStates', 'kind']); + expect(message).toContain("picklist: 'invoice_kind'"); + }); + + it('refuses an empty list', () => { + const message = refusedAt(invoice({ status: [] }), ['closedStates', 'status']); + expect(message).toContain('empty list'); + }); + + it('refuses a value that is not one of the field\'s options, located at the value', () => { + const message = refusedAt(invoice({ status: ['paid', 'closed'] }), ['closedStates', 'status', 1]); + expect(message).toContain("'closed', which is not an option of `status`"); + }); + + it('refuses a value the list repeats, located at the repeat', () => { + const message = refusedAt(invoice({ status: ['paid', 'void', 'paid'] }), ['closedStates', 'status', 2]); + expect(message).toContain("lists the value 'paid' twice"); + }); + + it('refuses a key that is not a field name, and a list of non-strings, by the key\'s own shape', () => { + expect(ObjectSchema.safeParse(invoice({ Status: ['paid'] })).success).toBe(false); + expect(ObjectSchema.safeParse(invoice({ status: [1] })).success).toBe(false); + expect(ObjectSchema.safeParse(invoice({ status: 'paid' })).success).toBe(false); + }); + + it('judges each field on its own: one issue per offending entry, the sound entry untouched', () => { + const parsed = ObjectSchema.safeParse(invoice({ status: ['paid'], approval_status: ['done'], state: ['x'] })); + expect(parsed.success).toBe(false); + if (parsed.success) return; + expect(parsed.error.issues.map((i) => i.path)).toEqual([ + ['closedStates', 'approval_status', 0], + ['closedStates', 'state'], + ]); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — a field or option a declaration still names is not removed or retyped', () => { + // The object's next version is judged whole, so each edit below leaves a + // declaration that names what the edit took away, and the edit is refused. + it('refuses removing the field', () => { + const before = invoice(ADR_EXAMPLE); + expect(ObjectSchema.safeParse(before).success).toBe(true); + const { approval_status: _removed, ...rest } = before.fields; + const message = refusedAt({ ...before, fields: rest }, ['closedStates', 'approval_status']); + expect(message).toContain('cannot be removed or renamed while the declaration names it'); + }); + + it('refuses retyping the field', () => { + const message = refusedAt( + invoice(ADR_EXAMPLE, { approval_status: { type: 'text', label: 'Approval' } }), + ['closedStates', 'approval_status'], + ); + expect(message).toContain('cannot be retyped while the declaration names it'); + }); + + it('refuses making the field multi-value', () => { + refusedAt( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', multiple: true, options: STATUS_OPTIONS } }), + ['closedStates', 'status'], + ); + }); + + it('refuses removing an option the declaration lists', () => { + const message = refusedAt( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', options: STATUS_OPTIONS.slice(0, 2) } }), + ['closedStates', 'status', 1], + ); + expect(message).toContain('cannot be removed while the declaration lists it'); + }); + + it('CONTROL: removing an option the declaration does not list lands', () => { + const parsed = ObjectSchema.safeParse( + invoice(ADR_EXAMPLE, { status: { type: 'select', label: 'Status', options: STATUS_OPTIONS.slice(1) } }), + ); + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — every door refuses at the same path', () => { + it('the save and publish door (the `object` metadata schema)', () => { + const schema = getMetadataTypeSchema('object'); + expect(schema).toBeDefined(); + const bad = schema!.safeParse(invoice({ status: ['closed'] })); + expect(bad.success).toBe(false); + if (bad.success) return; + expect(bad.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', ['closedStates', 'status', 0]]]); + expect(schema!.safeParse(invoice(ADR_EXAMPLE)).success).toBe(true); + }); + + it('the stack door, inside `objects`', () => { + const manifest = { + id: 'com.example.closedstates', + name: 'closed-states-test', + version: '1.0.0', + type: 'app' as const, + namespace: 'crm', + }; + const bad = ObjectStackDefinitionSchema.safeParse({ manifest, objects: [invoice({ state: ['paid'] })] }); + expect(bad.success).toBe(false); + if (bad.success) return; + expect(bad.error.issues.map((i) => [i.code, i.path])).toEqual([['custom', ['objects', 0, 'closedStates', 'state']]]); + expect(ObjectStackDefinitionSchema.safeParse({ manifest, objects: [invoice(ADR_EXAMPLE)] }).success).toBe(true); + }); +}); + +describe('[ADR-0162 D1] `closedStates` — a line object', () => { + it('a `master_detail` line needs no declaration, and may declare its own', () => { + const line = (closedStates?: unknown) => ({ + name: 'invoice_line', + fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'invoice' }, + line_status: { type: 'select', label: 'Line status', options: [{ label: 'Open', value: 'open' }, { label: 'Shipped', value: 'shipped' }] }, + }, + ...(closedStates === undefined ? {} : { closedStates }), + }); + expect(ObjectSchema.safeParse(line()).success).toBe(true); + expect(ObjectSchema.safeParse(line({ line_status: ['shipped'] })).success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/closed-states.ts b/packages/spec/src/data/closed-states.ts new file mode 100644 index 00000000000..2cb1f6a8cdb --- /dev/null +++ b/packages/spec/src/data/closed-states.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; + +// [ADR-0162 D1] The authoring half of `ObjectSchema.closedStates`: the +// declaration is judged against the object's own field map, at parse, so every +// door — `defineStack`, a raw `.parse()`, the metadata save and publish door — +// refuses a declaration that cannot be evaluated. Declared in its own module, +// outside the `data` barrel, so the function does not join the package's +// published exports (the `stage-field-kinds.ts` precedent). + +/** One closing field's declaration as the author wrote it: field name → its closing values. */ +type ClosedStatesInput = Record; + +/** The example every refusal ends on: the shape ADR-0162 D1 gives. */ +const CLOSED_STATES_EXAMPLE = + "e.g. `closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }`"; + +/** + * [ADR-0162 D1] `closedStates` names, for each field of THIS object, the list + * of that field's values that close a record. A record is closed when any + * listed field holds one of its listed values; the engine reads it off the + * stored row, so a declaration it cannot evaluate would parse and close + * nothing (ADR-0049: declared = enforced). Refused, one located issue each, + * judged against the AUTHORED field map: + * + * - at `['closedStates', ]`: a key that names no field of the object — + * also the shape a field REMOVED under a standing declaration leaves; + * - at `['closedStates', ]`: a field that is not a single-value + * `select` — another type, a `multiple: true` select (its row value is a + * list, so "holds one of the values" has no single reading), or a select + * RETYPED under a standing declaration; + * - at `['closedStates', ]`: a select that declares no inline + * `options` (a `picklist`-backed select's values are not declared on this + * object, so the listed values cannot be checked here — this is the one + * door every save passes, so it is refused rather than let through + * unjudged, as `stageField` is); + * - at `['closedStates', ]`: an empty list — it closes nothing; + * - at `['closedStates', , ]`: a value that is not one of the + * field's option values — also the shape an option REMOVED under a standing + * declaration leaves — and a value the list repeats. + * + * Not judged here, on purpose: the key's own shape (a map of string lists), + * which the schema refuses before this runs; a `state_machine` rule on the + * field, in either direction (D1: the rule says which moves are legal, the key + * says when the record stops accepting a caller's writes); a line object, + * which declares nothing to be closed with its master and may declare its own. + */ +export function refuseDishonestClosedStates( + ownName: unknown, + closedStates: unknown, + fields: unknown, + ctx: z.RefinementCtx, +): void { + if (closedStates === null || typeof closedStates !== 'object' || Array.isArray(closedStates)) return; + const objectName = typeof ownName === 'string' ? ownName : ''; + const fieldMap = fields !== null && typeof fields === 'object' ? (fields as Record) : {}; + const prescription = + '`closedStates` maps a stored, single-value `select` field of this object to a non-empty list of ' + + `that field's own option values, each listed once (${CLOSED_STATES_EXAMPLE}).`; + + for (const [fieldName, values] of Object.entries(closedStates as ClosedStatesInput)) { + if (!Array.isArray(values)) continue; + const at = ['closedStates', fieldName]; + const head = `Object \`${objectName}\` declares \`closedStates.${fieldName}\``; + if (!Object.prototype.hasOwnProperty.call(fieldMap, fieldName)) { + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but the object declares no field \`${fieldName}\`. A field a closed-state declaration names ` + + 'cannot be removed or renamed while the declaration names it: remove the entry from `closedStates` ' + + `first, or name a field the object declares. ${prescription}`, + }); + continue; + } + const def = fieldMap[fieldName] as + | { type?: unknown; multiple?: unknown; options?: unknown; picklist?: unknown } + | null + | undefined; + const type = def !== null && typeof def === 'object' ? def.type : undefined; + if (type !== 'select' || def?.multiple === true) { + const what = type === 'select' ? 'a `multiple: true` `select`' : `a \`${String(type)}\` field`; + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but \`${fieldName}\` is ${what}, not a single-value \`select\`: a record is closed when the ` + + 'field holds one of the listed values, so the field must hold exactly one stored value. A field a ' + + 'closed-state declaration names cannot be retyped while the declaration names it. ' + + prescription, + }); + continue; + } + if (!Array.isArray(def?.options)) { + const source = typeof def?.picklist === 'string' ? `takes its options from \`picklist: '${def.picklist}'\`` : 'declares no inline `options`'; + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head}, but \`${fieldName}\` ${source}, so whether each listed value is one of its options cannot ` + + `be checked here. Declare the field's options inline on \`${fieldName}\`. ${prescription}`, + }); + continue; + } + if (values.length === 0) { + ctx.addIssue({ + code: 'custom', + path: at, + message: + `${head} with an empty list, which closes no record. List at least one value of \`${fieldName}\`, ` + + `or remove the entry. ${prescription}`, + }); + continue; + } + const declared = new Set( + (def.options as Array<{ value?: unknown } | null>) + .map((o) => (o !== null && typeof o === 'object' ? o.value : undefined)) + .filter((v): v is string => typeof v === 'string'), + ); + const seen = new Set(); + values.forEach((value: unknown, index: number) => { + if (typeof value !== 'string') return; + const path = [...at, index]; + if (seen.has(value)) { + ctx.addIssue({ + code: 'custom', + path, + message: `${head} lists the value '${value}' twice. List each closing value once.`, + }); + return; + } + seen.add(value); + if (declared.has(value)) return; + ctx.addIssue({ + code: 'custom', + path, + message: + `${head} lists '${value}', which is not an option of \`${fieldName}\` (its options: ` + + `${[...declared].map((v) => `'${v}'`).join(', ') || 'none'}). An option a closed-state declaration ` + + `lists cannot be removed while the declaration lists it. ${prescription}`, + }); + }); + } +} diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index e5fe30e0779..b4c432a5b6d 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1684,6 +1684,7 @@ export const HookContextSchema = lazySchema(() => z.object({ */ provenance: z.object({ flowRunId: z.string().optional().describe('Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request.'), + flowRootRunId: z.string().optional().describe('Id of the root run of the flow-run tree `flowRunId` belongs to: the run the tree was started on, above every `subflow` child and `map` item run (equal to `flowRunId` on a run with no parent). Copied from `ExecutionContext.flowRootRunId`, which only the automation engine sets, beside `flowRunId`. Provenance, not authorization: lets a hook recognize a write by any run of one tree — the approvals plugin passes the runs of an approval through the hold it keeps between two steps on an object that declares `closedStates` (ADR-0162 D5).'), attributedUserId: z.string().optional().describe('The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth `update-member-role` call the identity adapter executes as `isSystem`. ATTRIBUTION ONLY: the audit writer records it as `sys_audit_log.user_id`; no security middleware reads it, and it never becomes the subject the write is authorized as.'), performedByClientId: z.string().optional().describe('[ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, the `client_id` of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in `session.userId`. Copied from `ExecutionContext.performedBy.clientId`, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like `attributedUserId`: the audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork.'), performedByAgentId: z.string().optional().describe('The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves.'), diff --git a/packages/spec/src/data/object.metadata-form.ts b/packages/spec/src/data/object.metadata-form.ts index 529d106111b..5bd6c0c7770 100644 --- a/packages/spec/src/data/object.metadata-form.ts +++ b/packages/spec/src/data/object.metadata-form.ts @@ -556,6 +556,10 @@ export const objectForm = defineMetadataForm({ // machine it usually follows: the same CEL code row the field form // gives the field key. { field: 'uiReadonlyWhen', type: 'code', language: 'expression', colSpan: 2, helpText: "CEL predicate over the record (e.g. record.status in ['confirmed', 'done']) — while it is TRUE, people cannot edit any field of an existing record anywhere in the console (the edit dialog, the record page, grids, kanban, calendar and Gantt drag, the timesheet); a new record's create dialog is not judged. A field that sets its own hand lock (uiReadonly turned on, or uiReadonlyWhen) is judged by that instead, so uiReadonlyWhen: false on a field keeps it editable; uiReadonly turned off does not, and the field follows this lock. Actions, imports, the API and flows still write every field, judged by the object's validations. Reads the record's own columns. The in-app assistant acting for a person does not honour it yet." }, + // [ADR-0162 D1] The states that close a record, beside the state + // machine and the hand lock: a map from a select field to its closing + // values, the same JSON row `validations` is edited in. + { field: 'closedStates', widget: 'json', colSpan: 2, helpText: 'States in which a record is closed, as a map from a single-value select field of this object to the list of its option values that close the record, e.g. { "status": ["paid", "void"], "approval_status": ["approved"] }. While a record is closed, no one but the system edits or deletes it, or adds, edits, moves or removes its lines. Each field needs its options declared on it; each value must be one of them, listed once. A field or option named here cannot be removed or retyped until it is taken out of this map.' }, // #19332 (flight G2b of ruling record 5861442317) — the object's // declarative timeline milestones (ADR-0052 §5b.2), beside `validations`: // a milestone fires on a field reaching a value, the same transition a diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index fb03dd2559b..24f451fea03 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -31,6 +31,7 @@ import { RECORD_PAGE_BUILTIN_TABS, relatedListEntryHidden, relatedListEntryName, // [#23809] The stage-field option-kind rule, in its own module so the AI // blueprint object (`ai/solution-blueprint.zod.ts`) runs this same refinement. import { refuseStageFieldWithoutKinds } from './stage-field-kinds'; +import { refuseDishonestClosedStates } from './closed-states'; // [#32763] The `icon` leaf, shared with the AI blueprint object. import { OBJECT_COLOR_SCHEMA, OBJECT_ICON_SCHEMA } from './object-icon'; // [#36366] The action arrangement per scope (pinned, more), shared with the object extension. @@ -4931,6 +4932,45 @@ const ObjectSchemaBase = strictObject( */ uiReadonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — every field of an existing record is read-only BY HAND while TRUE: the console surfaces a field's own `uiReadonlyWhen` locks (the edit dialog, record-page inline edit and the stage path, the highlight-strip chip, grid inline edit and multi-row save, kanban column drag, calendar drag, the Gantt, the timesheet cell, the line-item grid) do not let a person edit the record, while REST, import, action and flow writes keep every field, judged by the object's validations. e.g. P`record.status in ['confirmed', 'done']` on an order moved by Confirm / Cancel actions. A default for every field: a field that declares `uiReadonly: true` or its own `uiReadonlyWhen` is judged by that instead, so a field whose own `uiReadonlyWhen` is P`false` stays editable inside a locked record; `uiReadonly: false` is not such a declaration and the field follows the object lock. A create is not judged. A predicate the console cannot evaluate locks every field that inherits it. Same scope as a field's `readonlyWhen`: the record's OWN columns. The engine never reads this key."), + /** + * [ADR-0162 D1] The states in which a record of this object is CLOSED: a map + * from a field of this object to the list of that field's values that close + * the record. A record is closed when ANY listed field holds one of its + * listed values, read off the stored row (D2): nothing is stored for it. + * Two fields are the ordinary case — an approval mirrors its outcome into + * one field, the business status lives in another: + * `{ status: ['paid', 'void'], approval_status: ['approved'] }`. + * + * In a closed state the record and its direct `master_detail` lines are + * closed to change for every caller that is not a system context (D3–D5): + * no update or delete of the record, no line created, updated, deleted or + * moved. The line object declares nothing to be closed with its master, and + * may declare its own `closedStates` for a line that closes on its own. + * + * Each key names a stored, single-value `select` field of this object with + * inline `options`; each listed value is one of them; a list is not empty + * and repeats nothing. A declaration that breaks one of those rules is + * refused at parse and publish, and so is removing or retyping a field, or + * removing an option, that a declaration still names + * (`refuseDishonestClosedStates`, `./closed-states.ts`). Optional: an object + * without the key behaves exactly as before. No tie to a `state_machine` + * rule in either direction. + */ + closedStates: refuseRecordProtoKey( + z.record(FieldNameKeySchema, z.array(z.string())), + 'closedStates', + ).optional().describe( + 'States in which a record is CLOSED: a map from a stored, single-value `select` field of this object to ' + + 'the list of that field\'s option values that close the record, e.g. { status: [\'paid\', \'void\'], ' + + 'approval_status: [\'approved\'] }. A record is closed when ANY listed field holds one of its listed ' + + 'values, read off the stored row. While closed, the record and its direct master_detail lines are ' + + 'closed to change for every caller that is not a system context: the record is not updated or ' + + 'deleted, and no line is created, updated, deleted or moved. The field must declare inline options; ' + + 'each listed value is one of them; a list is not empty and repeats nothing. A field or option a ' + + 'declaration names cannot be removed or retyped while it names it. A line object declares nothing to ' + + 'be closed with its master, and may declare its own. Independent of any state_machine rule on the field.', + ), + /** * Display & UI Hints (Data-Layer) */ @@ -5588,6 +5628,10 @@ const ObjectSchemaBase = strictObject( // lifecycle `kind` — the same door: only the object knows which field is // its stage. refuseStageFieldWithoutKinds(object.name, object.stageField, object.fields, ctx); + // [ADR-0162 D1] Each `closedStates` key names a single-value `select` of + // THIS object with inline options, and each listed value one of them — the + // same door: only the object holds the field map. See the helper's docblock. + refuseDishonestClosedStates(object.name, object.closedStates, object.fields, ctx); // [cloud#3652 ruling D3] Each `renamedFrom` entry names one earlier key of // its field — not its own, not a live sibling's, not one another field // claims, once — the same door: only the object holds the field map. diff --git a/packages/spec/src/kernel/execution-context.zod.ts b/packages/spec/src/kernel/execution-context.zod.ts index b152d4eafa7..f403964057f 100644 --- a/packages/spec/src/kernel/execution-context.zod.ts +++ b/packages/spec/src/kernel/execution-context.zod.ts @@ -614,6 +614,26 @@ export const ExecutionContextSchema = lazySchema(() => z.object({ */ flowRunId: z.string().optional(), + /** + * Id of the ROOT run of the tree {@link flowRunId} belongs to: the run the + * tree was started on, at any depth of `subflow` children and `map` item + * runs below it (ADR-0162 Execution item 7, "The root run"). On a run with + * no parent it equals {@link flowRunId}. Server-constructed by the automation + * engine beside {@link flowRunId}, from the root run it stamps on every run + * of the tree, and carried wherever {@link flowRunId} is carried — never + * client-supplied. Absent where {@link flowRunId} is, and on a run the + * engine could not place in a tree. + * + * Provenance, NOT authorization, exactly like {@link flowRunId}. It exists so + * a hook can tell a write made by ANY run of one tree from an unrelated + * caller: the approvals plugin holds a record between two steps of an + * approval on an object that declares `closedStates`, and lets through the + * writes of that approval's own runs, which it knows by the root run its + * requests record (ADR-0162 D5, "the hold"). Surfaced to hooks as + * `HookContext.provenance.flowRootRunId`. + */ + flowRootRunId: z.string().optional(), + /** * Suppress record-change AUTOMATION (autolaunched flow triggers: * record-after-insert / -update / -delete) for writes made under this diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 71d861938f2..4e82aa99c0e 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -698,6 +698,101 @@ describe('operation message catalog — the record-lock refusal', () => { }); }); +/** + * [ADR-0162 D8] The engine's closed-state lock (`409 RECORD_LOCKED`): one wire + * code with the pending lock, its own two sentence families. The emitter is + * pinned on a real engine in `packages/qa/dogfood/test/closed-state-refusal-sentence.test.ts`, + * and on the wire in `packages/qa/dogfood/test/closed-state-refusal-wire.dogfood.test.ts`. + */ +describe('operation message catalog — the closed-state refusal (ADR-0162 D8)', () => { + /** The four forms, the placeholder contract of `record_locked*`, key for key. */ + const RECORD = { + record_closed: ['{{object}}', '{{title}}'], + record_closed_untitled: ['{{object}}'], + record_closed_unlabeled: ['{{title}}'], + record_closed_opaque: [], + } as const; + /** The delete refused for what it would also remove. */ + const DELETE = { + record_closed_delete_blocked: ['{{object}}', '{{title}}', '{{blockingObject}}'], + record_closed_delete_blocked_untitled: ['{{object}}', '{{blockingObject}}'], + record_closed_delete_blocked_opaque: [], + } as const; + const ALL = { ...RECORD, ...DELETE }; + const PENDING_TWIN: Record = { + record_closed: 'record_locked', + record_closed_untitled: 'record_locked_untitled', + record_closed_unlabeled: 'record_locked_unlabeled', + record_closed_opaque: 'record_locked_opaque', + }; + + it('every locale the catalog carries defines all seven, each with exactly its own placeholders', () => { + const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); + expect(locales).toEqual(expect.arrayContaining(['en', 'zh-CN', 'ja-JP', 'es-ES'])); + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, placeholders] of Object.entries(ALL)) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([...placeholders]); + } + } + }); + + it('is translated: no locale but en repeats the English sentence', () => { + for (const locale of Object.keys(BUILTIN_OPERATION_MESSAGES).filter((l) => l !== 'en')) { + for (const key of Object.keys(ALL)) { + expect(BUILTIN_OPERATION_MESSAGES[locale][key], `${locale}.${key}`).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]); + } + } + }); + + it('is not the pending lock\'s sentence in any form or locale: a closed document has no approval to wait for', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, twin] of Object.entries(PENDING_TWIN)) { + expect(catalog[key], `${locale}.${key}`).not.toBe(catalog[twin]); + } + for (const key of Object.keys(ALL)) { + // The pending lock's own word for its cause, per locale. + expect(catalog[key], `${locale}.${key}`).not.toMatch(/approval|审批|承認|aprobación/i); + } + } + }); + + it('carries no wire code, metadata key or API vocabulary in any form or locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + expect(catalog[key], `${locale}.${key}`).not.toMatch(/RECORD_LOCKED|closedStates|master_detail|_id\b|cascade/i); + } + } + }); + + it('says something different from every other key, in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of Object.keys(ALL)) { + const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v); + expect(others, `${locale}.${key}`).not.toContain(catalog[key]); + } + } + }); + + it('renders the caller locale with the labels and title it is given, and falls back to en for a locale the catalog lacks', () => { + const zh = renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title: 'INV-0042' } }, { locale: 'zh-CN' }); + expect(zh).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_closed.replace('{{object}}', '发票').replace('{{title}}', 'INV-0042')); + const ja = renderOperationMessage( + { messageKey: 'record_closed_delete_blocked_untitled', params: { object: '取引先', blockingObject: '請求書' } }, + { locale: 'ja' }, + ); + expect(ja).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].record_closed_delete_blocked_untitled.replace('{{object}}', '取引先').replace('{{blockingObject}}', '請求書')); + expect(renderOperationMessage({ messageKey: 'record_closed_opaque' }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en.record_closed_opaque); + }); + + it('a deployment translation override wins, under the shared `errors.` address, and a title is printed as written', () => { + const translate = (k: string) => (k === operationMessageTranslationKey('record_closed') ? '{{object}}《{{title}}》已归档' : k); + const title = 'Q{{object}}'; + expect(renderOperationMessage({ messageKey: 'record_closed', params: { object: '发票', title } }, { locale: 'zh-CN', translate })) + .toBe(`发票《${title}》已归档`); + }); +}); + /** * #34699 — the user's half of three platform refusals whose `message` stays the * developer sentence: the by-id not-found, the filter-oracle guard and the diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index b8f3a5ed690..1af55734adc 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -16,7 +16,8 @@ * refusal (`approval_recall_not_submitter`; emitter conversion is #11993's * half) — and the unique-constraint refusal (`409 UNIQUE_VIOLATION` on the * wire, the engine's `DuplicateRecordError`) — and the `userMessage` of the - * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3). The catalog is the seat for the rest of the family as they are + * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3) — and the engine's + * closed-state lock (`409 RECORD_LOCKED`, ADR-0162 D8). The catalog is the seat for the rest of the family as they are * localized — a second mechanism for the second producer is exactly what this * module exists to prevent. * @@ -41,6 +42,8 @@ * | `master_record_edit_denied` / `master_record_read_denied` (and their `_opaque` forms) | they wrote a `controlled_by_parent` record (a detail) without the edit access (or, where the detail asks it, the read access) its master record requires | ask the master record's owner, or an administrator | * | `field_edit_denied` / `field_edit_denied_opaque` | they changed a field their permissions do not let them edit | undo that change, or ask an administrator | * | `record_locked` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change a record an approval in progress holds | wait until that approval is complete | + * | `record_closed` (and its `_untitled`, `_unlabeled` and `_opaque` forms) | they tried to change or delete a record, or a line of a record, that is in one of its object's closed states | nothing: the document is final; a closed state is where it ends up | + * | `record_closed_delete_blocked` (and its `_untitled` and `_opaque` forms) | they tried to delete a record whose deletion would also remove a closed record, or a line of one | nothing: deleting it would change a final document | * * `record_write_denied` (commit aa5994e17) is NOT `record_access_denied` restated: the * sharing middleware's by-id write gate fires on a row the READ path already @@ -292,6 +295,50 @@ export function operationMessageTranslationKey(messageKey: string): string { * Their English is byte-identical to the fixed sentence the hook answered * before it was localized. * + * [ADR-0162 D8] The four `record_closed*` keys are the end user's sentence of + * the engine's closed-state lock (`409 RECORD_LOCKED`, `@objectstack/objectql` + * `closed-state-lock.ts`): a record in one of its object's declared closed + * states, or a line of one, refuses a caller's change or delete. Same code as + * the pending lock, its own sentences, because "wait until that approval is + * complete" is false for a closed document. The same four forms and the same + * placeholder contract as `record_locked*`: + * + * - `record_closed` takes `{{object}}` (the object's LABEL in the caller's + * locale) and `{{title}}` (the record's title as the WRITER would be + * served it under its own field permissions, never the title as stored); + * - `record_closed_untitled` takes `{{object}}` alone: for a record whose + * title the writer may not be served (its title field is one the + * writer's generic read does not return, or the security service is + * registered but cannot be resolved), for a title field whose value is + * not display text (a reference, or a field the object's `closedStates` + * names), for a write that matched rows by a predicate, and for a line + * write, where `{{object}}` is the MASTER's label (the engine reads the + * master's state to judge and reads nothing of it to word the refusal); + * - `record_closed_unlabeled` takes `{{title}}` alone, for an object with no + * label; + * - `record_closed_opaque` names nothing. + * + * The three `record_closed_delete_blocked*` keys are the same lock's + * sentence for a delete refused for what it would also remove: a closed + * record, or a line of one, in the set the delete was planned to remove. It + * names the record the caller asked to delete and the label of the object + * whose closed record stands in the way, and nothing else: no title, id or + * count of the closed records. + * + * - `record_closed_delete_blocked` takes `{{object}}` and `{{title}}` (the + * record asked to be deleted, its title as the caller is served it) and + * `{{blockingObject}}` (the label of the object in the way); + * - `record_closed_delete_blocked_untitled` drops `{{title}}`: where the + * caller is served no title for that record (its title field is one the + * caller's generic read does not return or is not display text, or the + * security service is registered but cannot be resolved), and where the + * delete names many records or names its rows by a predicate; + * - `record_closed_delete_blocked_opaque` names nothing, where either + * object has no label. + * + * None of the seven carries a record id, an API name or the state's value: a + * reader who may see the state reads it off the record. + * * Three keys are the `userMessage` of refusals whose `message` stays the * developer sentence (code, status and `message` unchanged). None takes a * placeholder, re-derived per site: @@ -472,6 +519,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This {{object}} is locked while an approval is in progress, and cannot be edited until that approval is complete', record_locked_opaque: 'This record is locked while an approval is in progress, and cannot be edited until that approval is complete', + record_closed: + "{{object}} '{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_unlabeled: + "'{{title}}' is closed, so it and its lines can no longer be changed or deleted", + record_closed_untitled: + 'This {{object}} is closed, so it and its lines can no longer be changed or deleted', + record_closed_opaque: + 'This record is closed, so it and its lines can no longer be changed or deleted', + record_closed_delete_blocked: + "{{object}} '{{title}}' cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines", + record_closed_delete_blocked_untitled: + 'This {{object}} cannot be deleted: deleting it would also remove a closed {{blockingObject}} or one of its lines', + record_closed_delete_blocked_opaque: + 'This record cannot be deleted: deleting it would also remove a closed record or one of its lines', record_not_found: 'This record does not exist, or you do not have access to it.', query_field_not_readable: 'This request filters, sorts or groups by a field you do not have access to. Remove that condition and try again, or contact your administrator if you need access.', @@ -605,6 +666,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」正在审批中,已被锁定,审批完成前无法编辑', record_locked_untitled: '该{{object}}正在审批中,已被锁定,审批完成前无法编辑', record_locked_opaque: '该记录正在审批中,已被锁定,审批完成前无法编辑', + record_closed: '{{object}}「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_unlabeled: '「{{title}}」已关闭,它及其明细行都不能再修改或删除', + record_closed_untitled: '该{{object}}已关闭,它及其明细行都不能再修改或删除', + record_closed_opaque: '该记录已关闭,它及其明细行都不能再修改或删除', + record_closed_delete_blocked: '无法删除{{object}}「{{title}}」:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_untitled: '无法删除该{{object}}:删除它会一并删除一条已关闭的{{blockingObject}}或其明细行', + record_closed_delete_blocked_opaque: '无法删除该记录:删除它会一并删除一条已关闭的记录或其明细行', record_not_found: '该记录不存在,或您无权访问它。', query_field_not_readable: '当前请求按您无权查看的字段筛选、排序或分组,请去掉该条件后重试,或联系管理员。', delegation_scope_violation: '此更改超出了您被委派管理的范围,如需更改请联系管理员。', @@ -734,6 +802,13 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_untitled: 'この{{object}}は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_opaque: 'このレコードは承認処理中のためロックされています。承認が完了するまで編集できません', + record_closed: '{{object}}「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_unlabeled: '「{{title}}」はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_untitled: 'この{{object}}はクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_opaque: 'このレコードはクローズ済みのため、明細を含めて変更も削除もできません', + record_closed_delete_blocked: '{{object}}「{{title}}」は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_untitled: 'この{{object}}は削除できません。削除すると、クローズ済みの{{blockingObject}}またはその明細も削除されます', + record_closed_delete_blocked_opaque: 'このレコードは削除できません。削除すると、クローズ済みのレコードまたはその明細も削除されます', record_not_found: 'このレコードは存在しないか、アクセスする権限がありません。', query_field_not_readable: 'この要求は、閲覧権限のない項目で絞り込み、並べ替え、またはグループ化しています。その条件を削除して再試行するか、アクセスが必要な場合は管理者にお問い合わせください。', @@ -886,6 +961,20 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Este registro de {{object}} está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', record_locked_opaque: 'Este registro está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', + record_closed: + 'El registro de {{object}} «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_unlabeled: + 'El registro «{{title}}» está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_untitled: + 'Este registro de {{object}} está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_opaque: + 'Este registro está cerrado, por lo que ni él ni sus líneas se pueden modificar ni eliminar', + record_closed_delete_blocked: + 'No se puede eliminar el registro de {{object}} «{{title}}»: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_untitled: + 'No se puede eliminar este registro de {{object}}: al eliminarlo también se eliminaría un registro cerrado de {{blockingObject}} o una de sus líneas', + record_closed_delete_blocked_opaque: + 'No se puede eliminar este registro: al eliminarlo también se eliminaría un registro cerrado o una de sus líneas', record_not_found: 'Este registro no existe o no tiene acceso a él.', query_field_not_readable: 'Esta solicitud filtra, ordena o agrupa por un campo al que no tiene acceso. Quite esa condición e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.', diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index b786b2c981f..a3518125e3e 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -3691,6 +3691,16 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/plugins/plugin-approvals/src/approval-mirror-unfinished-readings.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-approvals/src/approval-positions-name-authority.test.ts", "verb": "delete", @@ -6011,6 +6021,11 @@ "verb": "findOne", "pinned": 1 }, + { + "file": "packages/services/service-automation/src/step-child-runs.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/services/service-automation/src/stranded-run-object-store.test.ts", "verb": "delete",