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-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/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index e12d0d4f765..3639c51f278 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1559,6 +1559,32 @@ 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 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..8664adec081 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. - **Date**: 2026-11-26 - **Card**: [#36253](https://github.com/objectstack-ai/objectstack/issues/36253) (p2, `area:data`). Its rule, as the card carries it: @@ -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. 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 57f1d56abef..916082b9350 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -213,6 +213,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 8ea57a88785..949ee4da80a 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 0954d55f274..7393bc98fcf 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'; @@ -834,6 +835,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/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-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts index 7bf8bd0ec74..d5f3d62e880 100644 --- a/packages/plugins/plugin-approvals/src/approval-opening-check.ts +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -4,641 +4,25 @@ * [ADR-0162 D5, Execution item 7 "The check"] The check when an approval * opens, read off the approval's definition at its first request. * - * 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}: the service hands it the readers it - * has (the engine's object registry, the automation engine's flow lookup and - * node descriptors, whether the host runs a `job` service), 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. */ - calleeFlow(name: string, callerKey: string): 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; -} - -/** - * Read the approval whole and judge it. 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. + * 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 async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { - const gaps: OpeningGap[] = []; - if (!input.rootFlow) { - return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; - } - - // ── 1. Read every flow of the approval, to any depth ────────────────────── - 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[] = [input.rootFlow]; - flows.set(input.rootFlow.key, input.rootFlow.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 = await source.calleeFlow(name, 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); - } - - // ── 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(input.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; - }); -} +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';